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.

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 = datetime.datetime.now()

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

admin.site.register(Job, JobAdmin)

And there you have it!

Related Posts

1 comment:

  1. Hi Twig,
    useful and easy to implement tip. Thanks!

    ReplyDelete

Leave your thoughts ...
---
If you are having trouble with copy/pasting in comments, you need to sign in or click 'Preview'. For more information about this Firefox bug, see here.

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