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. MarkdownTextField by carljm 5 years, 9 months ago
  2. Markup Selection in Admin by jonathan 6 years, 8 months ago
  3. MarkupTextField by myles 5 years, 5 months ago
  4. Generic markup converter by ubernostrum 7 years, 1 month ago
  5. Markdown and Syntax Highlighting in Django by blinks 7 years, 1 month ago

Comments

(Forgotten your password?)