如何在Django中正确使用UUID id作为url参数?

时间:2019-10-01 08:33:05

标签: python django url

我一直在尝试将UUID4 ID传递到特定详细信息页面的网址中。

浏览Stackoverflow和其他站点之后,这是到目前为止我尝试过的操作:

  1. 将网址路径作为path('car/<uuid:id>/', views.CarDetailView.as_view(), name='car-detail'),

但这会引发错误:一般详细视图CarDetailView必须使用URLconf中的对象pk或slug调用。

由于uuid字段由字母和数字组成,因此我不能使用int。

  1. 所以我用了这个:

path(r"^(?P<car_model>\w+)/$", views.CarDetailView.as_view(), name='car-detail'),

会返回乱七八糟的URL:陈列室/%5E(%3FP09c32f72-5863-49fa-a42a-1d0fed274c4e%5Cw +)/ $

  1. 然后,我尝试还原为原始格式,但是在View类中使用了 def_object 方法。
def get_object(self):
    object = get_object_or_404(CarInstance,title=self.kwargs['car_model'])
    return object

但这会返回错误:“ / Showroom / car / 09c32f72-5863-49fa-a42a-1d0fed274c4e / 'car_model'“

models.py

class CarInstance(models.Model):
    manufacturer = models.ForeignKey('Manufacturer', on_delete=models.SET_NULL, null=True)
    car_model = models.CharField('Model', max_length=50, null=True)

views.py

class CarDetailView(generic.DetailView):
    model = CarInstance
    template_name = 'car_detail'

    def get_queryset(self):
         return CarInstance.objects.all()

    def get_object(self):
           object = get_object_or_404(CarInstance,title=self.kwargs['car_model'])
           return object

    def get_absolute_url(self):
            return reverse('showroom:car-detail', args=[str(self.pk)])

网址的格式应为 showroom / car / 09c32f72-5863-49fa-a42a-1d0fed274c4e / ,这将显示特定对象的详细信息视图。

有什么想法吗?

更新

根据以下答案,我将get_object覆盖更改为

    slug_field = 'title'
    slug_url_kwarg = 'car_detail'

但是我仍然得到相同的urlconf,必须以slug或int错误调用。我应该在模型中定义拖尾吗?

更新2

我已经更改了urlconf,但是出现了同样的错误。这是完整的追溯

Environment:


Request Method: GET
Request URL: http://localhost:8000/showroom/car/09c32f72-5863-49fa-a42a-1d0fed274c4e/

Django Version: 2.2.5
Python Version: 3.7.4
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'showroom']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\USER\Envs\torque\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\USER\Envs\torque\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\USER\Envs\torque\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\USER\Envs\torque\lib\site-packages\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\USER\Envs\torque\lib\site-packages\django\views\generic\base.py" in dispatch
  97.         return handler(request, *args, **kwargs)

File "C:\Users\USER\Envs\torque\lib\site-packages\django\views\generic\detail.py" in get
  106.         self.object = self.get_object()

File "C:\Users\USER\Envs\torque\lib\site-packages\django\views\generic\detail.py" in get_object
  47.                 "pk or a slug in the URLconf." % self.__class__.__name__

Exception Type: AttributeError at /showroom/car/09c32f72-5863-49fa-a42a-1d0fed274c4e/
Exception Value: Generic detail view CarDetailView must be called with either an object pk or a slug in the URLconf.

**另一个更新**

感谢@ruddra的帮助,我更改了路径以匹配slug_url_kwarg ='car_detail'现在看起来像这样:

path('car/<slug:car_detail>/', views.CarDetailView.as_view(), name='car-detail')

但是,现在页面出现了404错误。

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/showroom/car/09c32f72-5863-49fa-a42a-1d0fed274c4e/
Raised by:  showroom.views.CarDetailView
No car instance found matching the query

1 个答案:

答案 0 :(得分:3)

您不需要覆盖get_object()方法。您可以简单地使用slug_url_kwargslug_field。像这样:

class CarDetailView(generic.DetailView):
    model = CarInstance
    template_name = 'car_detail'
    slug_field = 'title'
    slug_url_kwarg = 'car_model'

更多信息可以在get_object()文档中找到。