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
An easier way of doing this is to use the
linebreaksfilter in the template.And just to clarify, even with the metaclass set,
to_pythonisn’t called from the template, but when the field is initially loaded from the database.