我可以用这种方式使用 urlize 过滤器吗?

发布于 2024-09-02 21:22:30 字数 264 浏览 4 评论 0原文

我可以用这种方式使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

另类 2024-09-09 21:22:36

如果您询问该片段在考虑语法的情况下是否有效,答案是肯定的,它不应该导致服务器 500 错误。

但是, urlize 的文档说,我引用:

请注意,如果 urlize 应用于
已经包含 HTML 的文本
标记,事情不会按预期进行。
仅将此过滤器应用于纯文本。

因此,假设首次创建对象时您的内容是纯文本,一切都应该没问题。

当您编辑现有对象时,调用 save 将对 body 属性的内容重新应用 urlize 过滤器,此时该属性不是纯文本。

据我所知,如果在内容中仅使用格式正确的 HTML 链接,这不会造成严重的后果,但文档仍然建议您应该只使用纯文本作为 urlize 的参数。

您可以在每次调用 urlize 之前删除由 urlize 插入的 HTML,例如使用 来自 activestate 的 MLStripper 类

from somelib import MLStripper
def save(self, force_insert=False, force_update=False):
    html_stripper = MLStripper()
    html_stripper.feed(self.body)
    self.body = urlize(html_stripper.get_fed_data())
    super(Post, self).save(force_insert, force_update)

至少理论上......

你真正应该做什么,除非你有非常充分的理由在模型中使用模板过滤器,就是在模板中使用urlize,例如:

{{ object.body|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:

Note that if urlize is applied to
text that already contains HTML
markup, things won't work as expected.
Apply this filter only to plain text.

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 the urlize filter on the content of body 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 to urlize for example using MLStripper class from activestate:

from somelib import MLStripper
def save(self, force_insert=False, force_update=False):
    html_stripper = MLStripper()
    html_stripper.feed(self.body)
    self.body = urlize(html_stripper.get_fed_data())
    super(Post, self).save(force_insert, force_update)

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:

{{ object.body|urlize }}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文