Overriding a Widget in the Django Admin Site, part 2
Posted in Uncategorized on October 9th, 2008 by varikinIn my last post, I showed a way to override a widget on the change/add page in the Django admin site. Now I will show how to process the marked up text.
First, here is what my model looks like:
#models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) raw_body = models.TextField() html_body = models.TextField() #other random non important attributes
As you can see, I am doing a blog application. The raw_body and html_body fields are the important ones, the former one holds the unprocesses marked up text, the later holds the processed text. Since a blog is read heavy application, I opted not to run the text through the markup processed for every view. I am keeping the original so it can be edited multiple times.
#utils.py
from django.utils.html import escape
from markdown import markdown
def mark_it_down(raw):
return markdown(escape(raw))
#models.py
from blog.utils import mark_it_down
class Post(models.Model):
#model fields from above
def save(self, **kwargs):
self.html_body = mark_it_down(self.raw_body)
super(Post, self).save(**kwargs)
The Post’s save method is overridden so that html_body can be set with the processed marked up text. I actually process the text in the mark_it_down method. This method first runs the raw text through django.utils.html.escape escape any <, >, &, “, etc with <, >, &, ", etc. Then it is run the the Markdown processor which generates the appropraite HTML. By the way, I am not displaying html_body field on the admin change/add page.
The last part is the preview with the MarkItUp! editor. If you set the previewParserPath variable in markitup/sets/markdown/set.js to a URL such as ‘/blog/markdown/preview/’, the MarkItUp will make an Ajax call to the URL with the markup text, and display the results. So I created a view to handle this:
#views.py
from django.http import HttpResponse
from moore.util import mark_it_down
def markdown_preview(request):
processed = ''
if request.method == 'POST':
processed = mark_it_down(request.POST.get('data'))
return HttpResponse(processed)
The text is in the data POST variable. The preview is displayed below the MarkItUp editor. I think this can be configured with the settings, but I haven’t played with that yet. I would like to not hard code the URL into the settings file, but then I would need to write a view for the js file and make the js file a template with the URL generated using a tag. Not hard, but I didn’t feel like doing that yet.
I believe that is everything I did, but if I missed anything or was unclear, please let me know.
