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

django - use urlpattern name in forms.ValidationError()

我有以下声明。

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' %} 格式而不是硬编码 urls?

谢谢。

您可以使用 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 ]})

使用reverse:

from django.core.urlresolvers import reverse

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

对于详细视图,我建议在模型上实施 get_absolute_url。此方法名称是 Django 约定。 Django 管理员将对其进行测试,如果存在,link 将对其进行测试。

# 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())