mark_safe and ValidationError params

57 views
Skip to first unread message

Andrew Pinkham

unread,
Feb 6, 2015, 4:33:25 PM2/6/15
to django...@googlegroups.com
I'm currently running Django 1.7.4. Provided the following clean function on a form:

def clean_slug(self):
new_slug = self.cleaned_data['slug'].lower()
if new_slug == 'invalid_value':
raise ValidationError(
# _ is ugettext
mark_safe(_('SlugField may not be '
'"%(slug_value)s" '
'for URL reasons.')),
params={
'slug_value':
mark_safe('<code>invalid_value</code>')})
return new_slug


I expect the HTML error output to read:

<li>SlugField may not be &quot<code>create_list</code>&quot; for URL reasons.</li>

Instead, the HTML output is:

<li>SlugField may not be &quot;&lt;code&gt;create_list&lt;/code&gt;&quot; for URL reasons.</li>

Meaning, the user sees the <code> tags as opposed to having them output as HTML.

The problem occurs when I remove the call to ugettext as well, and while I expect to only need to apply mark_safe to the value in params, I apply the function to all of the text above.

Am I doing something silly? How do I properly apply mark_safe to text passed to params of exceptions? What is the best-practice here?

Thanks,
Andrew

PS
I promise to add a code to my ValidationError before committing.

Mike Dewhirst

unread,
Feb 6, 2015, 6:30:15 PM2/6/15
to django...@googlegroups.com
On 7/02/2015 8:32 AM, Andrew Pinkham wrote:
> I'm currently running Django 1.7.4. Provided the following clean function on a form:
>
> def clean_slug(self):
> new_slug = self.cleaned_data['slug'].lower()
> if new_slug == 'invalid_value':
> raise ValidationError(
> # _ is ugettext
> mark_safe(_('SlugField may not be '
> '"%(slug_value)s" '
> 'for URL reasons.')),
> params={
> 'slug_value':
> mark_safe('<code>invalid_value</code>')})
> return new_slug

Have you tried removing mark_safe from the body of the method and
applying it at the end? ...

return mark_safe(new_slug)

Mike

Mike Dewhirst

unread,
Feb 6, 2015, 6:35:48 PM2/6/15
to django...@googlegroups.com
On 7/02/2015 10:29 AM, Mike Dewhirst wrote:
> How do I properly apply mark_safe to text passed to params of exceptions?

mark_safe returns a string-like object so if you embed it inside another
string it might get missed. I think it is best to apply mark_safe when
the return value won't be changed by other methods before being displayed.

Mike

Andrew Pinkham

unread,
Feb 8, 2015, 1:35:18 PM2/8/15
to django...@googlegroups.com
Thanks for the input, Mike.

I actually think the behavior I showed here is a bug, and have started a thread on the developer mailing list to talk about it.

https://groups.google.com/d/topic/django-developers/hs1Ikc8Tuuk/discussion

Andrew
Reply all
Reply to author
Forward
0 new messages