Django: Best practice for marking model fields as template safe

Now I have to do something like (template code):

object.name|safe 

There many times when I just forgot to add a safe filter. My questions:

  • These objects are sent and cleared by the user at the form level. Is there a reason I should be more careful about their safety?

  • If the answer for the above is β€œyou're good to go,” how do I make the model field safe by default? Remember to use the safe tag?

+4
source share
2 answers

safe is a templatetag related to HTML encoding, not object validation.
See Documentation

You need to use it only if you output a TextField with HTML data inside, for example a text field in which hyour users are populated with tinyMCE or CKEditor

0
source

As for No. 2, there is a poorly documented function called mark_safe that you can use. For example, in the custom form field that I wrote, I need to return an HTML code string for the label_from_instance method, so I return using mark_safe:

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

Source: https://habr.com/ru/post/1336783/


All Articles