Question

I'm trying to highlight some text in the validation message of a Django admin form.

The result is something like this

  valid_part
  <span style="background-color:yellow">invalid_part</span> 
  another_valid_part

I would like to leave as is <span ...> and </span>, but the valid_part, invalid_part of what the user just entered should be escaped as to avoid XSS.

Was it helpful?

Solution

You can do the following:

#views.py
from django.utils.html import escape
valid_part = "<i> hello1 </i>" #needs escaping
invalid_part = "<i> hello2 </i>" #needs escaping
error = "{0} <span style='background-color:yellow'>{1}</span>".format(escape(valid_part),escape(invalid_part))
return render_to_response('my.html',{"error":error})

In template:

#my.html
{{ error|safe }}

OTHER TIPS

In the view part:

 'parts': {
   'valid1': mark_safe(valid1),
   'valid2': mark_safe(valid2),
   'invalid': invalid,
 }

In the template:

{{ parts.valid1 }} {{ parts.invalid }} {{ parts.valid2 }}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top