简体   繁体   English

Django 错误:在 get 方法上找不到 404 页面

[英]Django error: 404 Page not found on get method

I am trying to get serialized data from endpoint localhost:8000/v1/test/uuid , but hitting a 404 error - what is wrong with below?我正在尝试从端点localhost:8000/v1/test/uuid获取序列化数据,但遇到404错误 - 下面有什么问题?

views.py视图.py

  • from uuid in response, get site objectuuid作为响应,获取站点 object
class Test(APIView):
    def get(self, request, *args, **kwargs):
        uuid = kwargs.get('uuid')
        resp = {'site': None}
        
        site = Site.objects.get(uuid=uuid)
        resp['site'] = SiteSerializer(site).data
        return Response(resp)

urls.py网址.py

from django.conf.urls import re_path

from rest_framework.routers import DefaultRouter

from site_config import views

router = DefaultRouter()

router.register(
    r'site',
    views.SiteViewSet,
    basename='site')


urlpatterns = [
    re_path(r'^v1/', include(router.urls)),
    re_path('test/<uuid:uuid>/', views.Test.as_view(), name='test'),
]

models.py模型.py

  • site id as the pk站点id作为 pk
class Site(models.Model):
    """
    Model that represents a Site
    """
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True)
    domain_name = models.CharField(max_length=255, unique=True)
    created = models.DateTimeField(editable=False, auto_now_add=True)
    modified = models.DateTimeField(editable=False, auto_now=True)

serializers.py序列化程序.py

class SiteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Site
        fields = [
            'uuid',
            'domain_name'
        ]

FYI - the endpoint was working when the views.py was returning all Sites, but it isn't working when I try to filter on uuid .仅供参考- 当views.py返回所有站点时端点正在工作,但当我尝试过滤uuid时它不工作。

views.py (previously working version) views.py(以前的工作版本)

class Test(APIView):
    def get(self, request, *args, **kwargs):
        resp = {'site': None}
        site = Site.objects.all()
        resp['site'] = SiteSerializer(site, many=True).data
        return Response(resp)

Error Message on Browser:浏览器上的错误消息:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/v1/test/7c018183-c952-4040-a450-e3cb58f09745/
Using the URLconf defined in site_config.urls, Django tried these URL patterns, in this order:

^v1/ ^site/$ [name='site-list']
^v1/ ^site\.(?P<format>[a-z0-9]+)/?$ [name='site-list']
^v1/ ^site/(?P<uuid>[^/.]+)/$ [name='site-detail']
^v1/ ^site/(?P<uuid>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='site-detail']
^v1/ ^$ [name='api-root']
^v1/ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root']
test/<uuid:uuid> [name='test']

urls.py网址.py

As this is a routing problem the first place to have a look should be the urls.py.由于这是一个路由问题,首先要看的地方应该是 urls.py。

Without recreating the app it looks like there are potentially three problems there:如果不重新创建应用程序,看起来可能存在三个问题:

Analysis分析

1. re_path 1. re_path

re_path is used, a regular Django path expression is provided.使用re_path ,提供了一个常规的 Django path表达式。 The django.urls documentation has some examples that speak for themselves. django.urls 文档中有一些不言而喻的示例。

2. the path itselt 2.路径本身

The URL path starts with v1/ while the provided configuration starts with test/ . URL 路径以v1/开头,而提供的配置以test/开头。

3. the order 3.订单

As the re_path for ^v1/ matches anything beginning with v1/ the order in the pattern is important.由于^v1/re_path匹配以v1/开头的任何内容,因此模式中的顺序很重要。

Anything that should available in that path must either be listed before the regex match, or be registered in the router.该路径中可用的任何内容都必须在正则表达式匹配之前列出,或者在路由器中注册。

Fix使固定

urlpatterns = [
    path('v1/test/<uuid:uuid>/', views.Test.as_view(), name='test'),
    re_path(r'^v1/', include(router.urls)),
]

FYI - the endpoint was working when the views.py was returning all Sites, but it isn't working when I try to filter on uuid.仅供参考 - 当 views.py 返回所有站点时端点正在工作,但当我尝试过滤 uuid 时它不工作。

As I do not have the breakpoint analysis for your views.py code I assume that your get method inside由于我没有对你的 views.py 代码进行断点分析,我假设你的 get 方法在里面

class Test(APIView):
    def get(self, request, *args, **kwargs):
        uuid = kwargs.get('uuid')
        resp = {'site': None}
        
        site = Site.objects.get(uuid=uuid)
        resp['site'] = SiteSerializer(site).data
        return Response(resp)

is not getting resolved by the patterns in your urls.py or the uuid is not getting through.未通过 urls.py 中的模式解决或 uuid 未通过。

If the case is former here what you can do is a direct mapping of the UUID inside the get method and avoiding the kwarg.get() by doing this如果这里的情况是以前的,你可以做的是在 get 方法中直接映射 UUID 并通过这样做避免kwarg.get()

class Test(APIView):
        def get(self, request, uuid, *args, **kwargs):
            uuid = uuid
            resp = {'site': None}
            
            site = Site.objects.get(uuid=uuid)
            resp['site'] = SiteSerializer(site).data
            return Response(resp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM