首页 > 解决方案 > Django urls with UUID issue

问题描述

Initial Error : When CustomerID was CharField in models.py :

Error Message :

after making changes to the model and making the CustomerID UUIDField getting the below error :

enter image description here

I am trying to redirect to the view based on the CustomerID but its not working for UUIDs. It was previously working fine with integers.

Please suggest.

url.py:

from django.urls import path, include
from . import views

urlpatterns = [
   path('create/', views.create, name='create'),
   path('<uuid:customer_id>', views.detail, name='detail'),
   path('search/customers/<uuid:customer_id>', views.detail, name='detail'),
   path('customers/<uuid:customer_id>', views.detail, name='detail'),
   path('edit/<uuid:customer_id>', views.edit, name='edit'),
   path('modify/<uuid:customer_id>', views.modify, name='modify'),
]

views.py

 @login_required
 def detail(request, customer_id):
     customer = get_object_or_404(CustomerMaster, pk=customer_id)
     return render(request, 'customers/detail.html',{'customer':customer})

models.py

   class CustomerMaster(models.Model):
         customerid = models.UUIDField(db_column='CustomerID', primary_key=True)  # Field name made lowercase.
         customernumber = models.CharField(db_column='CustomerNumber', max_length=50)  # Field name made lowercase.
         customername = models.CharField(db_column='CustomerName', max_length=50)  # Field name made lowercase.
          lastmodifiedutc = models.DateTimeField(db_column='LastModifiedUTC')  # Field name made lowercase.
          lastmodifiedby = models.CharField(db_column='LastModifiedBy', max_length=50)  # Field name made lowercase.
          active = models.BooleanField(db_column='Active')  # Field name made lowercase.
         customershortname = models.CharField(db_column='CustomerShortName', max_length=50, blank=True, null=True)  # Field name made lowercase.


      class Meta:
            managed = False
            db_table = 'Customer_Master'

            def __str__(self):
                return self.CustomerName

标签: djangopython-3.xdjango-modelsdjango-viewsdjango-urls

解决方案


根据文档,UUID 中的字母必须小写:

uuid - 匹配格式化的 UUID。为防止多个 URL 映射到同一页面,必须包含破折号并且字母必须小写。例如,075194d3-6885-417e-a8a8-6c931e272f00。返回一个UUID实例。


推荐阅读