The preceding section covered how to customize the change list of a model in the admin interface. Django also allows you to customize how the add and update forms for the model appear in the admin interface.
You might have noticed when editing Person objects in the iFriends project that the default object forms in the admin interface can become a bit clunky as you add more fields to the model.
Django gives you at least some control in the model over how add and update forms will appear in the admin interface: You use the fields attribute in the Admin class. The fields attribute gets set to a list of field groups that allow you to group and display fields under a label.
To group a model's fields, add the fields attribute to the model's Admin class, and add the fields in groups using the following syntax:
fields = ((<name>, {'fields': (<field list>)}),)
The following lines of code show an example of defining the fields attribute of the Admin class:
class Admin: fields = ( ('Info', {'fields':('name', 'number')}), ('Location', {'fields':('addr', 'city', 'state', 'zip')}), )
Did you Know?
The fields attribute also includes a collapse class that initially displays only the label for the group of fields with a link that expands the fields to a visible state. The following lines of code show an example of implementing the collapse class:
('Blogs', {'fields':('addr', 'city', 'state', 'zip'), 'classes': 'collapse'}),
Try It Yourself: Configure Add and Update Forms for a Model in the Admin InterfaceIn this section, you will modify the look of the People model in the admin interface to make it a bit more user-friendly. You will add the fields attribute to the Admin class of the People model and define labels for different groups of fields. You will also set the blogs and friends fields to initially be collapsed. Follow these steps to make the changes:
Listing 17.3. The Person Model Definition in the iFriends/People/models.py File
|