One of the exciting features Django 1.0 brings to the table is the integration of newform into the admin UI. Hat off to Brian, great work.
The essential workload in the Pattee’s admin UI is to input the meta information of the book, then link it to the eBook file. It is more convenient to take the advantage of Amazon Web Service, so the user scenario is:
- Search Amazon by keyword or ISBN
- Select the correct book
- Update the eBook file
- Save it to the database
It is straightforward to override the default template and implementation: redirect the admin URL to our own version of change_form.html template and add_view implementation, then save the object regardless the data integration; or we may reuse the infrastructure, and just implement our required function. Pattee takes the latter approach.
First, declare the BookAdmin and eBookAdmin in admin.py, and hook eBook inline:
model = eBook
extra = 1
form = BookForm
inlines = [eBookAdmin]
change_form_template = ‘book_change_form.html’
and don’t forget to register it to admin.site, which is required by Django 1.0.
Then in BookForm, we could override full_clean to provide the cleaned_data. And in BookAdmin, the following tricks will guard against duplication of Book instances:
instance = self.model.objects.get(isbn = form.cleaned_data[‘isbn’])
return super(BookAdmin, self).save_form(request, form, change)
That is all. You may consider to check out the source code for details: