1

I have the following statement.

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

This app has the following named url

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

Is there a way to use {%url 'group_detail' %} format in the href rather than hard-coded urls?

Thanks.

2 Answers 2

2

Use reverse:

from django.core.urlresolvers import reverse

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

For a detail view, I recommend to implement get_absolute_url on the model. This method name is a Django convention. The Django Admin will test for it and link to it if present.

# models.py
class ProductGroupModel(Model):

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

You can then easily use it with a model instance:

'Product type <a href="{url}">N/A already exists</a> for this combination.'.format(
    url=obj.get_absolute_url())
Sign up to request clarification or add additional context in comments.

Comments

1

You can use result of reverse function:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.