我可以用这种方式使用 urlize 过滤器吗?
我可以用这种方式使用 urlize 过滤器吗? :
from django.utils.html import urlize
def save(self, force_insert=False, force_update=False):
self.body = urlize(self.body)
super(Post, self).save(force_insert, force_update)
body 是一个文本字段。
Could I use urlize filter in this way? :
from django.utils.html import urlize
def save(self, force_insert=False, force_update=False):
self.body = urlize(self.body)
super(Post, self).save(force_insert, force_update)
body is a TextField.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您询问该片段在考虑语法的情况下是否有效,答案是肯定的,它不应该导致服务器 500 错误。
但是, urlize 的文档说,我引用:
因此,假设首次创建对象时您的内容是纯文本,一切都应该没问题。
当您编辑现有对象时,调用
save
将对body
属性的内容重新应用urlize
过滤器,此时该属性不是纯文本。据我所知,如果在内容中仅使用格式正确的 HTML 链接,这不会造成严重的后果,但文档仍然建议您应该只使用纯文本作为
urlize
的参数。您可以在每次调用
urlize
之前删除由urlize
插入的 HTML,例如使用 来自 activestate 的 MLStripper 类:至少理论上......
你真正应该做什么,除非你有非常充分的理由在模型中使用模板过滤器,就是在模板中使用
urlize
,例如:If you are asking if that snippet would work as far as syntax is considered the answer is yes, it should not cause server 500 error.
But, the documentation for urlize says, and I quote:
So assuming that your content is plain text when the object is first created everything should be fine.
When you edit an existing object, call to
save
would reapply theurlize
filter on the content ofbody
attribute which is not plain text at this point.As far as i can tell this would not cause serious grief if only properly formatted HTML links are used in content, but it is still suggested by the documentation that you should only use plain text as argument to
urlize
.You could strip the HTML inserted by the
urlize
each time before call tourlize
for example using MLStripper class from activestate:In theory at least...
What you should really do, unless you have very strong reason for using template filter in your model, is to use
urlize
in your template, for example: