Well I thought now was as good a time as any to make my first Django post. One of the best things about Django is its automatic admin interface, built very effectively from just your model objects in the ORM. What a good idea. Generally, even if a webapp isn’t there just to do CRUD, its backoffice tool almost certainly is. And even the most beautiful webapps generally have awful backoffice tools. Why? Because who the hell wants to spend their time writing a boring CRUD interface 3 people are going to see! And when does business even consider time for that sort of thing, non-customer-facing mean non-thought-about.
Here’s an example of the backoffice tool for What Ales You:
Pretty isn’t she (I presume admin interfaces have the same gender as ships?). To activate the admin interface ensure under settings.py that django.contrib.admin is included under INSTALLED_APPS and that in urls.py you have the relevant lines (they are marked with comments) included and uncommented. Then add a file called admin.py to each project where you wish to administer model objects. For example, mine for my beer project is currently:
from alephile.beer.models import Brewery, Beer, BeerRating, Media, BeerComment, UserProfile from django.contrib import admin admin.site.register(Brewery) admin.site.register(Beer) admin.site.register(BeerRating) admin.site.register(BeerComment) admin.site.register(Media) admin.site.register(UserProfile)
This tells Django which model objects I want to be able to edit. You’ll notice that my beer description is a normal text input which is a bit annoying, what I’d prefer is a textarea. To achieve this I need to add a ModelAdmin and a ModelForm. The ModelAdmin is a class telling Django how to administer a particular model object. Each ModelAdmin contains a ModelForm which tells it how to create the editing form. By default this just includes all editable fields, but now we are going to override the ModelAdmin and tell it to use a custom form instead. We end up with:
from alephile.beer.models import Brewery, Beer, BeerRating, Media, BeerComment, UserProfile from django.contrib import admin from django import forms class BeerModelForm( forms.ModelForm ): description = forms.CharField( widget=forms.Textarea ) class Meta: model = Beer class BeerAdmin( admin.ModelAdmin ): form = BeerModelForm admin.site.register(Brewery) admin.site.register(Beer, BeerAdmin) admin.site.register(BeerRating) admin.site.register(BeerComment) admin.site.register(Media) admin.site.register(UserProfile)
and an interface that looks like so. Easy when you know how but something I initially struggled to find out.
Your post was very helpful. Thanks!