Login

Render markdown to a separate model field

Author:
mindcruzer
Posted:
September 19, 2012
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

This function, meant to be used with the pre_save signal, will convert any markdown from a text field to it's corresponding html field.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.