reStructuredText Widget in Django Admin
While Django has great support for rendering standard markup languages, sometimes it can be difficult editing documents using a markup in the Django Admin. Several others (1, 2, 3) show how easy it is to edit Markdown, Textile, and even HTML, in the Django Admin using a WYSIWYG editor, such as markItUp! or TinyMCE.
Unfortunately, reStructuredText is not well support by most WYSIWYG editors. Nevertheless, we can improve the experience of editing reStructuredText in the Django Admin. One of the biggest improvements is switching the Textarea to use a monospace font to avoid issues caused by the heading underlines being too short. We can also customize the size of the Textarea.
In our app/admin.py
file, we can add a ModelForm
which overrides the
field that has the reStructuredText content (in this case,
description
). We then use this
ModelForm
as the form
in our subclass of
ModelAdmin.
Finally, we indicate that the ModelAdmin
subclass is associated with
the specific model that contains the reStructuredText content.
For the reStructuredText content field, description
, we change the
size to a width of 80 characters and the font to a monospace family.
Additionally, we add a quick link to the reStructuredText Quick
Reference.
from django import forms
from django.contrib import admin
from app.models import Entry
class EntryAdminForm(forms.ModelForm):
description = forms.CharField(widget=forms.Textarea(attrs={'rows':30,
'cols':80,
'style':'font-family:monospace'}),
help_text='<a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">reStructuredText Quick Reference</a>')
class Meta:
model = Entry
class EntryAdmin(admin.ModelAdmin):
form = EntryAdminForm
admin.site.register(Entry, EntryAdmin)