2017-05-03 15 views
0

Django的1.11NoReverseMatch與UUIDField

你能給我在這裏踢(以下回溯)?

models.py

class Image(CommonUrlMethodsMixin, GeneralModel): 
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) 

回溯:

Reverse for 'detail' with keyword arguments '{'pk': '718d5ff1-702c-4a81-a2a8-5cf59f1605e6'}' not found. 1 pattern(s) tried: ['images/(?P<pk>\\[\\w-]+)/$'] 

urls.py

urlpatterns = [ 
    url(r'^images/', include('images.urls.show_modify', namespace='images')), 
] 

images.urls.show_modify.py

urlpatterns = [ 
    url(r'^(?P<pk>\[\w-]+)/$', ImageDetailView.as_view(), name="detail"), 

] 

順便說一句,這個工程:

>>> im = Image.objects.get(pk='718d5ff1-702c-4a81-a2a8-5cf59f1605e6') 
>>> im 
<Image: ID 718d5ff1: , title sdfsadf> 

model_mixins.py

class CommonUrlMethodsMixin(): 
    """ 
    Models for applications whose urls can be resolved from the 
    application name and object pk: 

    framesgeneral:frame_detail, 
    framesgeneral:frame_update  
    """ 


    class CommonUrlMethodsMixin(): 
     def _get_url_helper(self, suffix): 
      """ 
      suffix - str. 

       Suffix choices: 
        1) detail; 
        2) update; 
        3) delete; 

      Prepares reverse string depending on what view we need. 
      """ 
      app = self._meta.app_label 

      return reverse("{0}:{1}".format(app, suffix), 
          kwargs={'pk': str(self.id)}) 

     def get_absolute_url(self): 
      return self._get_url_helper("detail") 

在外殼的另一個回溯:

>>> im.get_absolute_url() 
... 
    File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/urls/resolvers.py", line 497, in _reverse_with_prefix 
    raise NoReverseMatch(msg) 
django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with keyword arguments '{'pk': UUID('718d5ff1-702c-4a81-a2a8-5cf59f1605e6')}' not found. 1 pattern(s) tried: ['images/(?P<pk>\\[\\w-]+)/$'] 

回答

0

嘗試在你的URL模式移除方括號之前的反斜槓(\):

url(r'^(?P<pk>[\w-]+)/$', ImageDetailView.as_view(), name="detail"), 
+0

謝謝。加工。 – Michael

1

您應該將uuid作爲str來傳遞,而不是模型字段對象。

reverse(..., kwargs={'pk': your_instance.id.__str__()}) 

或者

..... {'pk': str(your_instance.id)} 
+0

好像是不工作。我編輯了我的問題:添加轉換爲字符串。沒有幫助。 – Michael