I've been trying to get syntax highlighting working in my simple Django (1.1) test app using Markdown (2.0.1) & Pygments (1.0). The idea is to generate HTML from the users input which is in markdown format and store both in the DB so I don't have to do the markdown to html translation during the fetch.
So far I have the markdown processing working but I cannot seem to get syntax highlighting working. My models.py looks like this:
from django.db import models
from django.contrib import admin
from markdown import markdown
class BlogPost( models.Model ):
title = models.CharField( max_length = 150 )
body = models.TextField()
body_html = models.TextField(editable=False, blank=True, null=True)
timestamp = models.DateTimeField()
def save(self):
self.body_html = markdown(self.body, ['codehilite'])
super( BlogPost, self).save()
class Meta:
ordering = ( '-timestamp', )
class BlogPostAdmin( admin.ModelAdmin ):
list_display = ( 'title', 'timestamp' )
admin.site.register(BlogPost, BlogPostAdmin)
So far testing just markdown syntax works but if I try something like the following I don't seen any syntax highlighting in the output or the output source:
:::python
from foo import bar
foobar = bar('foo')
I'd expect to see at least a set of code elements in the output source.
Fixed it! The code should have been indented four spaces not three!
I made multiple edits to test that out before asking the question but it would seem Firefox cached the page as using as a test post. As I had been using the windows keyboard shortcut to force a page reload not the mac keyboard shortcut, d'oh!
I spotted it was working when I made a new test post out of frustration with four space indenting and then inspected the page source.
It's better to store it in the database in markdown format, and then convert it to the presentation format you'd like (HTML) at display time. That way you can edit your data the same way you added it in the first place.
At the top of your template you should include:
{% load markup %}
Then use the template filter markdown.
{{ blog_post.body|markdown}}
Then just use css to make sure you have the proper formatting.
You also need to install the markdown package if you don't have it here.
And in your settings.py in your INSTALLED_APPS you should include 'django.contrib.markup'
For more information see this page.
As for why you don't see formatting, check the marked up source and make sure it is working correctly. i.e. make sure it is marking up properly. Then make sure you have the needed stylesheets.
Markdown format is the format before it is marked up.
You can also use JQuery to add a class to the marked up elements, so you can style the markdown text without affecting the rest of the page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With