django如何使用带有uuid字段的get_absolute_url

时间:2016-04-23 14:34:58

标签: django django-models django-templates

我有一个UUIDField的模型,当我使用以下`

<h3>
<a href="{{  box.get_absolute_url }}">{{ box.title }}</a>
</h3>` 

我收到此错误 Reverse for 'detail_box' with arguments '(UUID('29eec708-4ee6-4999-838d-712441876ac7'),)' and keyword arguments '{}' not found. 0 pattern(s) tried: []

models.py

@python_2_unicode_compatible
class Box(TimeStampModel):
    """
    Box model
    """
    def __str__(self):
        return self.title

    title = models.CharField(max_length=40, blank=True, null=True)
    identify = models.BooleanField(default=False)
    activate = models.BooleanField(default=False)
    slug = models.UUIDField(default=uuid.uuid4, editable=False)
    activation_key = models.UUIDField(default=uuid.uuid4, editable=False)

    def get_absolute_url(self):
        return reverse('suggies:detail_box',
                       args=[self.slug] 
                )

urls.py

urlpatterns = [
    url(r'^detail/(?P<slug>[0-9A-Za-z-]+)/$', views.detail_box, name='detail_box'),
    ...
]

my views.py

def detail_box(request, slug):
    boxes = get_object_or_404(Box, slug=slug)
    return render( request, 'suggies/detail.html', {'boxes':boxes} )

1 个答案:

答案 0 :(得分:2)

get_absolute_url方法中,将UUID实例转换为str。这样的事情应该有效。

def get_absolute_url(self):
    return reverse('suggies:detail_box', args=[str(self.slug)])