django: Customise the admin form for models

Customising the admin form can be a bit tricky as the documentation is a bit scarce on that issue.

What I needed to do was add a checkbox which renews the object to the current timestamp.

However, the checkbox is not part of the model, and won't show up unless you specify a custom form. To specify a custom form, fill in the ModelAdmin.form attribute.

Upon saving, we override ModelAdmin.save_model() so it knows how to use the data from the new field elements.

Below is the working source for a customised form.

import datetime

from django import forms
from django.contrib import admin

class JobForm(forms.ModelForm):
renew = forms.BooleanField(label = 'Renew post')

class Meta:
model = Job

class JobAdmin(admin.ModelAdmin):
form = JobForm

def save_model(self, request, obj, form, change):
if change and form.cleaned_data['renew']:
obj.published =

return super(JobAdmin, self).save_model(request, obj, form, change), JobAdmin)

And there you have it!

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog