Using a template tag in a form error message in Django

My code contains:

Class GroupForm(forms.ModelForm):
    ....
    def clean_name(self):
        ....
        raise forms.ValidationError(mark_safe('....<a href="{% url edit %}">click here</a>.'))

I want to include the url that kwargs should pass in my error message. I use mark_safe so that my anchor text characters are not deleted.

Currently, the url that is created on the page is (current url directory) / {% url edit%}. It just treats my tag as text.

Is there a way to make this url behave normally?

+3
source share
2 answers

Technically, but it's a little confusing. ValidationErrorplain text expects, so you have to give it anyway. But you can make the text yourself before submitting it to ValidationError:

Class GroupForm(forms.ModelForm):
    ....
    def clean_name(self):
        from django.template import Context, Template
        t = Template('....<a href="{% url edit %}">click here</a>.')
        c = Context()
        raise forms.ValidationError(t.render(c))

Template.render() , . , , Context .

: , URL-, reverse, , , .

0

, . {% url %} Python: django.core.urlresolvers.reverse:

from django.core.urlresolvers import reverse

...

    url = reverse("edit")
    raise forms.ValidationError(mark_safe('....<a href="%s">click here</a>.' % url))
0

All Articles