Render markdown to a separate model 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. Pre-delete signal function for deleting files a model by mindcruzer 8 months ago
  2. MarkdownTextField by carljm 4 years, 10 months ago
  3. "Autoconnect" model decorator, easy pre_save and post_save signal connection by bendavis78 2 years, 9 months ago
  4. Generic markup converter by ubernostrum 6 years, 2 months ago
  5. Revisiting Pygments and Markdown by djypsy 5 years, 9 months ago

Comments

(Forgotten your password?)