views:

30

answers:

1

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.

+1  A: 

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 }}
rebus
Yes I wanted to use urlize in the template but I have read in a book about django ( The definitive guide about django ) that is convenient save the body formatted with tags and without tags ( in 2 TextField ) for better performance :-\
xRobot
For performance reasons using two fields would be benedictory for large body of text, but if the text is large enough to cause performance loss, you should probably rethink the way you are handling your data. For example, you could use text editor on your input so the user defines the links before the text is saved to the database. Also i am having hard time finding this reference to `urlize` in Definitive guide to Django.
rebus