django: Customise the admin form for models

1 Comment

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.

01.import datetime
02. 
03.from django import forms
04.from django.contrib import admin
05. 
06.class JobForm(forms.ModelForm):
07.  renew = forms.BooleanField(label = 'Renew post')
08. 
09.  class Meta:
10.    model = Job
11. 
12.class JobAdmin(admin.ModelAdmin):
13.  form = JobForm
14. 
15.  def save_model(self, request, obj, form, change):
16.    if change and form.cleaned_data['renew']:
17.      obj.published = datetime.datetime.now()
18. 
19.    return super(JobAdmin, self).save_model(request, obj, form, change)
20. 
21.admin.site.register(Job, JobAdmin)

And there you have it!

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