views:

36

answers:

2

I want to subclass models.TextField so I can return the text to the template with occurences of \r\n replaced with <br />. I don't want the <br />'s stored in the database, however. What method is called to retrieve the field's data when invoked from the template?

I tried this, but it doesn't seem to work:

class HTMLTextField(models.TextField):
    def to_python(self, value):
        value = super(HTMLTextField, self).to_python(value)
        value = value.replace('\r\n', '<br />')
        value = value.replace('\n', '<br />')
        return mark_safe(value)

Thanks, Pete

+1  A: 

I was missing this:

__metaclass__ = models.SubfieldBase

Well, I was missing this in my subclass, but I found a built-in template tag that does this {{ textfield|linebreaksbr }}, doh!

slypete
+2  A: 

An easier way of doing this is to use the linebreaks filter in the template.

And just to clarify, even with the metaclass set, to_python isn't called from the template, but when the field is initially loaded from the database.

Daniel Roseman