Where should markdown parsing code live in a Django app?

295 views Asked by At

I am using WMD editor in the django admin. I have written a simple parser (regex mostly) so I can catch specific tags in the markdown and insert HTML accordingly. My problem is that I need access to the Django object itself.

Currently I'm overriding Model.save() and calling Model.process_markdown()

def process_markdown(self):
    p = re.compile("\[\[\s*(?P<tag>image):(?P<id>[\d,]+)\s*\]\]")
    processed = p.sub(partial(render_markdown, self), self.body_markdown)
    return markdown.markdown(processed)

The result is then saved into a Model.rendered field on my model. If you notice I have a render_markdown function being called. Thats stored in a file called util.py in my app and does all the real work.

Everything is working but this seems like there should be a better way. I know I can tie into markdown for custom tags and do this a cleaner but I have to beable to access the django object and I as I reference related inline objects. As far as I can tell there is not a way for me to do this.

Is there a better way to organize this?

1

There are 1 answers

1
Jeremy Dunck On

Beware that markdown allows HTML to be tunneled through. If you do this, you probably want markdown(html, safe_mode='escape') If you're allowing untrusted sources to insert .body_markdown, you will need to sanitize that input via something like bleach: http://pypi.python.org/pypi/bleach