The Python framework's Django Learning notes (14)

Source: Internet
Author: User

Django Site Management (cont.)

I want to update yesterday, who had thought yesterday was working day! I'm not going to puke. The trough worked overtime to 11 O ' Day yesterday, the demand increases undoubtedly let me wait for the egg ache unceasingly, reminds of a limerick:

When the moon has, the wine asked friends. I wonder if this version is going to be out tonight. I want to tear down the refactoring, and fear the project manager, yelling at me late at night. Delete and change the code, as if not saved ...

Take a deep breath, look at the screen, tears in the stream. Should not hate, who did not forget to save code? People have joys and sorrows, the code has lost conflict, this matter ancient difficult whole. I wish people long, leader don't find out.

Nonsense less, into today's topic, Django Site management learning begins.

Custom list

Let's take a step further: Customize the Display field in the list of Author modules. The list defaults to display the __unicode__ ()of the object in the query results.

1 classAuthor (models. Model):2First_Name = models. Charfield (max_length=30)3Last_Name = models. Charfield (max_length=40)4email = models. Emailfield (Blank=true, verbose_name='e-Mail')5 6**def __unicode__(self):* *7**returnU'%s%s'% (Self.first_name, self.last_name) * *

PS: The part within the asterisk is the new part of the change, which is not mentioned later.

After the change is complete, the effect is as follows:

We can improve on this basis and add other fields to change the display of the list. This page should be handy, like this: you can see the author's email address in this list. If you can sort by last name or first name, that's better.

For this purpose, we will define a Modeladmin class for the Author module. This class is the key to custom management tools, and one of the most basic things is allowing you to specify the fields in the list. Open admin.py and modify:

1  fromDjango.contribImportAdmin2  fromBooks.modelsImportPublisher, Author, Book3 4**classAuthoradmin (admin. Modeladmin):* *5**list_display = ('first_name','last_name','Email')**6 7 Admin.site.register (Publisher)8**admin.site.register (Author, authoradmin) * *9Admin.site.register (book)

Nagging the code:

First, a new class Authoradmin, which is a subclass derived from Django.contrib.admin.ModelAdmin , holds a custom configuration of a class for use by management tools. We have only customized one:list_display, which is a tuple of field names for the list display. Of course, these field names must be in the module.

We then modified the admin.site.register () call to add the authoradminafter Author . You can understand this: register the Author module with the authoradmin option.

Finally, theadmin.site.register () function accepts a modeladmin subclass as the second argument. If you omit the second argument, Django will use the default option. This is the case with Publisher and book registrations. ]

Fix this stuff, and then refresh the author list page, you'll see three columns in the list: Last name, surname, and email address. Also, click the column header of each column to sort the column. As shown below:

  

Next, let's add a quick query bar. Append search_fieldsto authoradmin , such as:

1 class authoradmin (admin. Modeladmin):2     list_display = ('first_name'last_name  "email")3     **search_fields = ('  first_name'last_name') * *

Refresh your browser and you'll see a query bar at the top of the page. (see Figure 6-9.) The modified list page We just made, added a query box based on the name query. As the user wants, it is case-sensitive and retrieves a query box for two fields. If the query "bar", then the name contains Barney and the last name of the author records containing Hobarson will be retrieved.

  

Create a few more data to play the search.

Next, let's add some filters to the book list page.

1  fromDjango.contribImportAdmin2  fromBooks.modelsImportPublisher, Author, Book3 4 classauthoradmin (admin. Modeladmin):5List_display = ('first_name','last_name','Email')6Search_fields = ('first_name','last_name')7 8**classBookadmin (admin. Modeladmin):* *9**list_display = ('title','Publisher','publication_date')**Ten**list_filter = ('publication_date',)** One  A Admin.site.register (Publisher) - Admin.site.register (Author, authoradmin) -**admin.site.register (book, bookadmin) * *

Since we are dealing with a range of options, we have created a separate modeladmin class:bookadmin. First, we define a list_displayto make the page look better. We then use the list_filter field tuple to create the filter, which is located on the right side of the list page. Django provides a quick filter for date fields that includes: Today, the past seven days, the current month, and this year. These are often used by developers.

Custom Edit Form

As with custom lists, editing forms can be customized in many ways.

First, we'll start by customizing the field order. By default, the order of the fields in the form is consistent with the definition in the module. We can change it by using the fields option in the modeladmin subclass:

1 classbookadmin (admin. Modeladmin):2List_display = ('title','Publisher','publication_date')3List_filter = ('publication_date',)4Date_hierarchy ='publication_date'5ordering = ('-publication_date',)6**fields = ('title','authors','Publisher','publication_date')**

When you are finished, the edit form displays the fields in the order specified. It looks a lot more natural-the author is behind the title. The order of the fields is of course related to the entry order of the data entries, and each form is different.

With the fields option, you can exclude fields that you don't want to be edited by others, as long as you don't choose the field (s) you don't want to edit. You can use this function when your ADMI user is only trusted to change a certain portion of your data, or if your data is automatically processed by some external program. For example, in the book database, we can hide publication_dateto prevent it from being edited.

1 classbookadmin (admin. Modeladmin):2List_display = ('title','Publisher','publication_date')3List_filter = ('publication_date',)4Date_hierarchy ='publication_date'5ordering = ('-publication_date',)6**fields = ('title','authors','Publisher')**

This way, the publication date cannot be changed on the edit page. This feature is useful if you are an editor and do not want the author to postpone the publication date.

When a user adds a new book to a form that does not contain complete information, Django simply sets publication_date to Noneto ensure that the field satisfies the null=true condition.

Another common editing page customization is for many-to-many fields. As we see on the book editor page, "Many-to-many fields" are displayed as multiple boxes. Although the multi-box is logically the most appropriate HTML control, it is less useful. If you want to select multiple items, you must also press the CTRL key (the MAC is the Command key). Although the Administration tool has added comments (help_text), it still looks awkward when it has hundreds of options.

A better way is to use filter_horizontal. Let's add it to the bookadmin and see how it works.

1 classbookadmin (admin. Modeladmin):2List_display = ('title','Publisher','publication_date')3List_filter = ('publication_date',)4Date_hierarchy ='publication_date'5ordering = ('-publication_date',)6**filter_horizontal = ('authors',)**

Refresh the book edit page and you'll see an ingenious JavaScript filter in the author area that allows you to retrieve the options and then move the selected authors from the available box to the chosen box, and you can move it back. The interface diagram is as follows:

  

It is highly recommended to use filter_horizontalfor many-to-many fields that have more than 10 options. This is much more useful than a multi-marquee. You can use filter_horizontalon multiple fields, just specify the name of each field in the tuple.

  The modeladmin class also supports the filter_vertical option. It works like Filter_horizontal , except that the controls are arranged vertically, not horizontally. As for which, it's just a matter of personal preference.

  The filter_horizontal and filter_vertical options can only be used on many-to-many fields , not foreignkey fields. By default, the administrative tool uses a drop-down box to display the Foreign key field. However, as with many-to-many fields, there are times when you don't want to tolerate the overhead of loading and displaying these options. For example, our book database is inflated to a record of thousands of publishers, so that the book's add page takes longer to load because it has to load each publishe and display it in a drop-down box.

The solution to this problem is to use the "raw_id_fields" option. It is a tuple containing a foreign key field name that contains fields that will be displayed as "text boxes" instead of "drop-down boxes". The effect is as follows:

1 classbookadmin (admin. Modeladmin):2List_display = ('title','Publisher','publication_date')3List_filter = ('publication_date',)4Date_hierarchy ='publication_date'5ordering = ('-publication_date',)6Filter_horizontal = ('authors',)7**raw_id_fields = ('Publisher',)**

  

In this input box, what do you enter? The database ID number of Publisher. Given that people don't usually remember these database IDs, the Admin tool provides a magnifying glass icon for you to enter. Clicking on that icon will pop up a window where you can select the Publishe you want to add.

At this point, the Django management site has finished learning. Today is to make new and write blog, one will also write another project detailed set, not many said, first sleep a sleep.

The Python framework's Django Learning notes (14)

Related Article

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.