django - 在forms.ValidationError()中使用urlpattern名称

时间:2017-07-03 10:20:50

标签: django django-urls

我有以下声明。

raise forms.ValidationError({'product_type':
    [mark_safe('Product type <a href="/group/detail/%d/">N/A already exists</a> for this combination.' % na[0].product_group.id) ]})

此应用程序具有以下名称url

url(r'^detail/(?P<pk>[0-9]+)/$', views.ProductGroupDetail.as_view(), name='group_detail'),

有没有办法在href中使用{%url 'group_detail' %}格式而不是硬编码的网址?

感谢。

2 个答案:

答案 0 :(得分:2)

使用reverse

from django.core.urlresolvers import reverse

url = reverse('group_detail', args=[pk])

对于详细视图,我建议在模型上实现get_absolute_url。此方法名称是Django约定。 Django Admin将测试它并链接到它(如果存在)。

# models.py
class ProductGroupModel(Model):

    def get_absolute_url(self):
        return reverse('group_detail', args=[self.pk])

然后,您可以轻松地将其与模型实例一起使用:

'Product type <a href="{url}">N/A already exists</a> for this combination.'.format(
    url=obj.get_absolute_url())

答案 1 :(得分:1)

您可以使用reverse功能的结果:

url = reverse('group_detail', kwargs={'pk': na[0].product_group.id})
[mark_safe('Product type <a href="%s">N/A already exists</a> for this combination.' % url ]})