使用UUIDField的NoReverseMatch

时间:2017-05-03 13:32:09

标签: django

Django 1.11

你能不能在这里给我一脚(下面的追溯)?

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")

shell中的另一个回溯:

>>> 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-]+)/$']

1 个答案:

答案 0 :(得分:1)

尝试删除网址模式中方括号前的反斜杠(\):

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