如何修复 django“找不到页面 (404)”错误(“Django 尝试了这些 URL 模式...空路径与其中任何一个都不匹配。”)

问题描述 投票:0回答:1

作为 Django 的新手,我遇到了和我之前的许多人一样的问题。如果您没有立即将我的问题标记为双重问题,我将不胜感激,因为我检查了那些旧帖子建议的修复,但不幸的是没有结果。

当我启动服务器时,我得到:找不到页面(404)。

Using the URLconf defined in shops_online.urls, Django tried these URL patterns, in this order:

admin/
api/organizations/ [name='organizations-list']
api/organizations/<int:id>/shops_file/ [name='get-shops-file']
api/shops/<int:id>/ [name='shop-view']
api/v1/token/ [name='token_obtain_pair']
api/v1/token/refresh/ [name='token_refresh']
api/v1/token/verify/ [name='token_verify']
docs/ [name='schema-swagger-ui']
The empty path didn’t match any of these.

这是我的观点.py:

from django.shortcuts import render
from rest_framework.views import APIView
from .models import Shop, Organization
from shop.serializers import OrganizationSerializer, ShopSerializer
from rest_framework.response import Response
from rest_framework import status
import pandas as pd
import logging
from django.http import HttpResponse

from django.core.mail import send_mail
from background_task import background
from background_task.models import Task

from background_task.models import Task
from .tasks import send_email_task

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

@api_view(['GET'])
@permission_classes([IsAuthenticated])
class OrganizationListView(APIView):
    def get (self, request):
        try:
            organizations = Organization.objects.filter(is_deleted=False)
            serializer = OrganizationSerializer(organizations, many=True)
            # logging
            logging.info('GET request was successful')
            return Response(serializer.data, status=status.HTTP_200_OK)
        except Exception as e:
            logging.error(f'An error occurred while executing the request: {e}')
            return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['PUT'])
@permission_classes([IsAuthenticated])
class ShopView(APIView):
    def put (self, request, id):
        try:
            shop = Shop.objects.get(id=id)
            serializer_shop = ShopSerializer(shop, data=request.data)
            if serializer_shop.is_valid():
                serializer_shop.save()
                
                @background(schedule=10)
                def send_email_background_task(recipient, subject, message):
                    send_email_task(email, subject, message)

                email = '[email protected]'
                subject = 'Subject of the email'
                message = 'Message body of the email'
                
                send_email_background_task(email, subject, message)
                
                logging.info('PUT request was successful')
                return Response(serializer_shop.data)
            else:
                return Response(serializer_shop.errors, status=status.HTTP_400_BAD_REQUEST)
        except Shop.DoesNotExist:
            logging.error(f'Shop with id={id} not found')
            return Response(f'Shop with id={id} not found', status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            logging.error(f'An error occurred while executing the request: {e}')
            return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
class shops_file(APIView):
    def shops_file(self, request, id):
        try:
            organization = Organization.objects.get(id=id)
            shops_csv = organization.shop_set.all()
            data_shops = [{'id': shop.id, 'name': shop.name} for shop in shops_csv]
            df = pd.DataFrame(data_shops, columns=["id", "name"])
            filename = f"shops_{'organization_id'}.xlsx"
            df.to_excel(filename, index=False)
            logging.info('The request was succesful')
            return Response(open(filename, 'rb'), as_attachment=True)
        except Organization.DoesNotExist:
            logging.error(f'Organization with id={id} not found')
            return Response(f'Organization with id={id} not found', status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            logging.error(f'An error occurred while executing the request: {e}')
            return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)

ve checked urls.py for several times, but no bug was supposed to be there. I
有两个网址:shops_online.urls.py(我的项目的网址)和shop.urls.py(我的应用程序的网址)。

shops_online.urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('shop.urls')),
]

shop.urls.py:

from django.contrib import admin
from django.urls import path
from shop.views import OrganizationListView, ShopView, shops_file
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView 
from rest_framework import routers
from shop import views

yasg_view = get_schema_view(
    openapi.Info(
        title="Snippets API",
        default_version = "v1",
        description = "Descriiption",
        terms_of_service = "https://www.google.com/policies/terms/",
        contact = openapi.Contact(email="[email protected]"),
        license = openapi.License(name="BSD Licence"),
    ),
    public=True,
)

urlpatterns = [
    path('api/organizations/', views.OrganizationListView, name='organizations-list'),
    path('api/organizations/<int:id>/shops_file/', views.shops_file, name='get-shops-file'),
    path('api/shops/<int:id>/', views.ShopView, name='shop-view'),
    path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
    path('docs/', yasg_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]

python django http-status-code-404 django-urls
1个回答
0
投票

问题出在你的shops_online.urls.py中的shop.urls.py上,你有

path('', include('shop.urls'))
,而在shop.urls.py中:你没有一个路径,即path('', view.example, name='索引'),这就是造成这种情况的原因!添加 path('', view.example, name='index') 并映射将解决您的问题的相对视图。请在下面找到更新的代码:

(“Django 尝试了这些 URL 模式...空路径与其中任何一个都不匹配。”)

shops_online.urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('shop.urls')),
]

shop.urls.py:

from django.contrib import admin
from django.urls import path
from shop.views import OrganizationListView, ShopView, shops_file
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView 
from rest_framework import routers
from shop import views

yasg_view = get_schema_view(
    openapi.Info(
        title="Snippets API",
        default_version = "v1",
        description = "Descriiption",
        terms_of_service = "https://www.google.com/policies/terms/",
        contact = openapi.Contact(email="[email protected]"),
        license = openapi.License(name="BSD Licence"),
    ),
    public=True,
)

urlpatterns = [
    path('', view.example, name='index'),
    path('api/organizations/', views.OrganizationListView, name='organizations-list'),
    path('api/organizations/<int:id>/shops_file/', views.shops_file, name='get-shops-file'),
    path('api/shops/<int:id>/', views.ShopView, name='shop-view'),
    path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
    path('docs/', yasg_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]
© www.soinside.com 2019 - 2024. All rights reserved.