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

w8f9ii69  于 2023-03-13  发布在  Go
关注(0)|答案(3)|浏览(170)

我一直在尝试将UUID 4 ID传递到特定详细信息页面的URL中。
在浏览Stackoverflow和其他网站后,以下是我到目前为止的尝试:
1.将url路径作为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(% 3FP 09 c32 f72 -5863- 49 fa-a42 a-1d0fed274c4e% 5Cw+)/$
1.然后我尝试恢复到原来的样子,但是使用了View类中的一个def_object方法。

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

但这会返回错误:“在/展厅/汽车/09 c32 f72 -5863- 49 fa-a42 a-1d 0 fed 274 c4 e/ '汽车型号'处出现按键错误”

型号.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)

查看次数.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)])

URL的格式应该是showroom/car/09 c32 f72 -5863- 49 fa-a42 a-1d 0 fed 274 c4 e/,这将打开特定对象的详细视图。
有什么想法吗?

更新

根据下面的答案,我将get_object重写更改为

slug_field = 'title'
    slug_url_kwarg = 'car_detail'

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

更新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
jw5wzhpr

jw5wzhpr1#

你不需要重写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()**文档。

q35jwt9p

q35jwt9p2#

1.在www.example.com中创建get_absolute_url()models.py:

def get_absolute_url(self):
    return reverse('car-detail', args=[str(self.<yourUUIDFieldName>)]) # self.car_model

1.在www.example.com中设置URLurls.py:

urlpatterns = [
    path('car/<uuid:yourUUIDFieldName>/', # 'car:<uuid:car_model'>
    views.CarDetailView.as_view(), name='car-detail'),
]

1.尝试更改视图:

class CarDetailView(DetailView):
    model = CarInstance
    slug_field = '<uuid:yourUUIDFieldName>' # -> 'car_model'
    slug_url_kwarg = '<uuid:yourUUIDFieldName>' # -> 'car_model'
    template_name = 'car_detail.html'

1.此外,尝试这个,如果你喜欢:

import uuid
car_model = models.UUIDField(default=uuid.uuid4, unique=True)

car_model替换yourUUIDFieldName,检查一下这个是否有效,以我的方式,我不知道,我和其他人一样是个初学者,希望你能从中得到一些东西

w8ntj3qf

w8ntj3qf3#

虽然这已经太晚了。但是,有人会发现它很有帮助。你可以修改你的模块如下:
您的模特.py

import uuid as uuid_lib
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)
    uuid = models.UUIDField(
        db_index=True,
        default=uuid_lib.uuid4,
        editable=False, 
        unique=True,)

网址.py

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

最后,您的意见.py

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

相关问题