Changing How Models Are Edited
Changing How Models Are Edited. You can customize more than just the change list page. The screens used to add or change an object are based on a
ModelForm. Django automatically generates the form based on the model being edited.
You can control which fields are included, as well as their order, by editing the
fields option. Once more, modify your
PersonAdmin object, adding a
The Add and Change pages for
Person now put the
first_name attribute before the
last_name attribute, even though the model itself specifies the other way around.
ModelAdmin.get_form() is responsible for creating the
ModelForm for your object. You can override this method to change the form. Here, you can see the method being added to
Now, as you can see onscreen, when the Add or Change page is displayed, the label of the
first_name field is customized. Changing the label might not be sufficient to prevent vampires from registering as students.
If you don’t like the
ModelForm that Django admin created for you, then you can use the
form attribute to register a custom form.
Here some more changes have been made to
This code enforces additional validation on the
Person Add and Change pages.
ModelForm objects have a rich validation mechanism. In this case, the
first_name field is being checked against the name
ValidationError prevents students with this name from registering.
By changing or replacing the
ModelForm object, you can fully control the appearance and validation of the pages you use to add or change object pages.
02:38 With more control over the data that’s presented and how it’s edited and changed, the next area to investigate is changing the templates which control the appearance of the admin area pages, and that’s what you’ll be seeing in the next section.
Become a Member to join the conversation.