Using a template tag within 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 a url that I need to pass kwargs to in my error message. I'm using mark_safe so that my anchor text characters don't get escaped开发者_运维知识库.
Currently the url that gets produced on the page is (current url directory)/{% url edit %} . Its just treating my tag as text.
Is there a way I can get this url tag to behave like normal?
Technically, but it's a tad convoluted. ValidationError
expects plain text, so you're going to have to give it that one way or another. But you can render the text yourself before feeding 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()
requires a context, which is why I just passed in an empty one. But if you have additional variables and such you also need to render, you can pass those into Context
in the form of a dictionary.
UPDATE: As Daniel Roseman mentions, this is unnecessary for URLs since you can just use reverse
, but if you need to render any other type of tag, this is the method you need.
You can do this, but there's no need to. The equivalent code for the {% url %}
tag in Python code is 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))
精彩评论