Write the first Django app, Part 5-custom administrator function

Source: Internet
Author: User

Custom admin form
This is enough to surprise us for several minutes, allCodeWe do not need to write.
When we call Admin. Site. Register (poll), Django only asks you to edit this object and "speculate" how to display it on the Management page.
In many cases, you may want to control admin styles and functions. You can tell Django the options when registering an object.
Let's take a look at how to re-Sort fields in the form editing. Use the following code to replace Admin. Site. Register (poll ):
Class polladmin (Admin. modeladmin ):
Fields = ['pub _ date', 'question']

Admin. Site. Register (poll, polladmin)
You will follow this mode-create an admin model object and pass it to admin. site. the second parameter of register () -- any time you need to modify the admin option, you must modify an object. The specific change above is that the "publication date" field is before the "Question" field:


Only two fields are not impressive, but when the admin form contains a large number of fields, selecting an intuitive sorting method is an important detail.
In addition, you may want to classify a large number of form fields into a field set:
Class polladmin (Admin. modeladmin ):
Fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub _ date']}),
]

Admin. Site. Register (poll, polladmin)
The first element of each tuple in a field set is the title of the field set. Now our form looks like this:


You can specify any HTML style for each field set. Django provides a "collapse" style that shows each specific field set as collapsed during initialization.
When a long form contains many fields that are not commonly used, this style is very practical:
Class polladmin (Admin. modeladmin ):
Fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub _ date'], 'class': ['collapse']}),
]

 
Add associated object
OK. We have a poll admin page. However, a poll has multiple choice, and the Management page does not display choices.
Okay.
There are two ways to solve this problem. The first method is to register admin choice, just as we registered poll. This is easy:
From mysite. Polls. Models import choice

Admin. Site. Register (choice)
"Choices" in Django admin is now available. This "add choice" looks like this:


in this form, the "Poll" field is a selection box that contains all poll of the database. Django knows that the foreign key represents a box in Admin. In our example, only poll has a foreign key. you also noted the "add another" link next to "Poll. Each object that contains a foreign key relationship with other objects will have this link. when you click "add another", you will get a group of forms with the "add poll" form. if you add a poll in the form and click "save", Django saves the poll to the database and dynamically adds it as an option to "add choise. but in fact, this is an inefficient way to add a choice object to the system. When you create a poll object, you can add choice directly to it. Let's implement it. register the Register () method of the Choice Model. Edit the registration code of Poll: class choiceinline (Admin. stackedinline): model = choice extra = 3

Class polladmin (Admin. modeladmin ):
Fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub _ date'], 'class': ['collapse']}),
]
Inlines = [choiceinline]

Admin. Site. Register (poll, polladmin)
The Code tells DJANGO: "The choice object is edited in the admin page of poll. By default, sufficient fields are provided for the three choice. "
Load the "add poll" page to see what it looks like:


It works like this: There are three columns associated with choice -- specified in extra -- each time you return to the "change" page of a created object, you will get three additional columns.
But there is still a small problem. It occupies too much space to display all input fields of the associated object choice. Django provides a tabulation to display associated objects;
You only need to modify the choiceinline statement:
Class choiceinline (Admin. tabularinline ):
#...
Using tabularinline (instead of stackedinline), the associated object is more compact, which is based on the table format:

Custom admin change list
Now the poll admin page is quite good. Let's optimize the "Change List" page -- it is used to display all the poll in the system.
This is what it looks like:


By default, Django displays STR () for each object (). But sometimes it will be more effective if we can display individual fields.
To do this, you only need to use the list_display admin option, which is a tuple used to display the field name as the column name on the object's change list page:
Class polladmin (Admin. modeladmin ):
#...
List_display = ('Question ', 'pub _ date ')
Just for good measure, let's also include the was_published_today custom method from tutorial 1:

Class polladmin (Admin. modeladmin ):
#...
List_display = ('Question ', 'pub _ date', 'was _ published_today ')
Now, the poll change list page looks like this:


You can click the column header to sort these values-except the was_published_today header, because sorting does not support output values of any method.
It is also noted that the was_published_today column header is its method name by default (replace spaces with underscores ). However, you can change this name by giving a brief attribute description for the method:
Def was_published_today (Self ):
Return self. pub_date.date () = datetime. Date. Today ()
Was_published_today.short_description = 'hhed today? '
Let's add another improvement to the poll change list page: filter. Add the following code to polladmin:
List_filter = ['pub _ date']
A "filter" sidebar is added to allow people to use the pub_date field to filter the change list:


The style displayed by this filter depends on the type of the field you want to filter.
Since pub_date is datetimefield, Django knows to give datetimefield a default filter:

"any date", "today", "past 7 days", "this month", "this year ".
now it is better. Let's add some search functions:
search_fields = ['question']
added a search box for the change list. When someone enters the search value, Django will retrieve the question field.
you can use multiple search fields-although like queries ensure readability and database efficiency.
finally, because the poll object contains a date, it is more convenient to perform the following operations. Add this line of code:
date_hierarchy = 'pub _ date'
it adds a date layered navigation on the Change List page. In the upper layer, it displays all available years. Then the month and day are displayed downward.
it is also a good time to pay attention to the free paging function provided by change lists.
50 records are displayed on each page by default. The paging, retrieval, filtering, date layering, and column header sorting of the change-list all work according to the expected results.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.