[英]Django: Best practice for marking model fields as safe for templates
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. 有很多次我只是忘记添加
safe
过滤器。 My questions: 我的问题:
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?
有什么理由我应该更加小心地标记它们的安全吗?
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? 无需记住使用
safe
标签?
In regards to #2, there is a poorly documented function called mark_safe that you can use. 关于#2,你可以使用一个名为mark_safe的文档很少的文档。 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:
例如,在我编写的自定义表单字段中,我需要返回一个包含label_from_instance方法的HTML代码的字符串,因此我使用mark_safe返回:
return mark_safe( '<span class="foo">Some HTML output</span>' )
safe
is a templatetag dealing with HTML encoding, not with object validation. safe
是一个处理HTML编码的模板标签,而不是对象验证。
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 如果您在内部输出带有HTML数据的TextField,则只需使用它,例如,用户填充tinyMCE或CKEditor的文本字段
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.