Could I use urlize filter in this 开发者_如何学Goway? :
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.
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 }}
精彩评论