import markdown
def render_markdown(sender, instance, *args, **kwargs):
'''
Renders markdown from a text field to a dedicated html field.
This is meant to be used with the pre_save signal.
'''
md = markdown.Markdown(safe_mode='escape')
for fieldname, _ in instance.__dict__.iteritems():
if fieldname.endswith("_html"):
fieldname_raw = fieldname[:fieldname.find('_html')]
field_raw = getattr(instance, fieldname_raw, None)
if field_raw:
setattr(instance, fieldname, md.convert(field_raw))
...
from django.db import models
from django.db.models.signals import pre_save
class SomeModel(models.Model):
...
biography = models.TextField()
biography_html = models.TextField()
...
# render markdown from biography to biography_html on save
pre_save.connect(render_markdown, sender=SomeModel)
Comments