2017-07-03 56 views
1

我有以下聲明。django - 在forms.ValidationError()中使用urlpattern名稱

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'), 

是否有使用{%url 'group_detail' %}格式在href,而不是硬編碼的網址的方法?

謝謝。

回答

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 ]}) 
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())