4

Right now I have to do something like (template code):

object.name|safe

There's many times where I just simply forget to add the safe filter. My questions:

  1. These objects are user submitted and cleaned at the form level. Is there a reason why I should be more careful about marking them safe?

  2. If the answer for above is "you're good to go", how do I make the model field safe by default? Without having to remember to use the safe tag?

2 Answers 2

5

In regards to #2, there is a poorly documented function called mark_safe that you can use. For example, in a custom form field I've written I need to return a string with HTML code for the label_from_instance method, so I return using mark_safe:

return mark_safe( '<span class="foo">Some HTML output</span>' )
1

safe is a templatetag dealing with HTML encoding, not with object validation.
See the documentation

You only have to use it if you're outputting TextField with HTML data inside, for example a text field that hyour users are filling with tinyMCE or CKEditor

2
  • 1
    To extend what Dominique has said, the safe filter is meant to mark something safe to the template renderer. By default, Django will escape all output on templates thinking the output is unsafe, meaning it could contain html/script code that you don't want the browser to interpret as code. If you do have a field with code in it that you want the browser to interpret, you use the safe tag to tell Django to output without any autoescaping.
    – Alex Kuhl
    Jan 24, 2011 at 15:10
  • Unfortunately the link is dead
    – jlandercy
    Feb 1 at 8:47

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.