Django1.7 Learning (III)

Source: Internet
Author: User
Brief Introduction:

Generating management websites for adding, modifying, and deleting content is a tedious task. For this reason, Django automatically creates a management interface based on the model.

Django is written in the news and editing room environment. There is a clear line between "content poster" and "public" websites. The website administrator uses this system to add news, events, and sports scores, which are displayed on a public website. Django solves the problem of creating a unified management interface for the website administrator to edit the content.

The management interface is not used by website visitors. It is prepared for the website administrator.

8. Create a management account

First, you must create a user who can log on to the Management page and run the following command:

python manage.py createsuperuser

Enter the expected username as required and press Enter. Here, the admin is used as an example.

Username : admin

Next, you will be prompted to enter the expected email address:

Email address: [email protected]

The last step is to enter the password. Enter the password twice as usual.

Password: **********Password (again): *********Superuser created successfully.
9. Start the development server and log on to the Management page.

The Django management interface is activated by default. Start the development server and start exploring it together.

As mentioned above, use the following command to enable the development server:

python manage.py runserver

Open the web browser to access the/admin/directory of the local domain name, such as the default http: // 127.0.0.1: 8000/admin/, and then you can see the following logon Interface

Because the translation function is enabled by default, the language is set to Chinese in settings. py. Therefore, the Chinese interface is displayed, which is the English interface by default.

Now you can use the superuser created previously to log on. Normally, you should see the following page

You can see some editable content, including group and user ). These are the core frameworks provided by Django by default.

10. Make the data of the poll application editable on the management website.

After careful observation, we can find that the created app does not appear on this management page. How can we make the app appear on the Management Interface? You only need to do one thing: register the question object with Admin.

OpenModify the polls/admin. py file to the following content:

from django.contrib import adminfrom polls.models import Questionadmin.site.register(Question)

Re-open the management page and you will find that our app appears on the Management page.

11. Exploring management functions

Click "questions". Now we are in the questions Change List page. This page displays all the question existing in the database and allows us to select and modify it, here we can see the created question: "What's up? "

Click "what's up? "Edit

  • The form is automatically generated based on the question model.
  • Different Model Field Types (datetimefield, charfield) correspond to the corresponding HTML input control, Django management knows how to represent each type of field
  • Every datetime has a javascript shortcut. The date has a "today" shortcut and a pop-up calendar, while the time has a "now" shortcut and a pop-up window listing common time options.
  • There are four well-known buttons to delete and save ......

If the date published is different from the creation time, it indicates that the time_zone value is not set correctly. After modification, restart.

Click the shortcut "today" and "now" to modify "date published", select "Save and edit" after modification, and click "History" in the upper right corner ", the management page lists all the modification records, including the time and user name of the user performing the modification.

12. Custom management forms

You have registered the question model through admin. Site. Register (question), and Django will automatically generate a default form. However, we usually want to customize the appearance and functions of the management form. In this case, we need to configure the object while registering it.

Next, let's take a look at how to sort fields in the editing form. Replace Admin. Site. Register (question) with the following line:

from django.contrib import adminfrom polls.models import Questionclass QuestionAdmin(admin.ModelAdmin):    fields = [‘pub_date‘, ‘question_text‘]admin.site.register(Question, QuestionAdmin)

We need to follow the following mode-create a model management object, and then input the second parameter to Admin. Site. Register ()-any configuration of the management interface should follow

The above modification makes the "posting time" appear on "question ".

Only two fields may not be too impressed, but it is very important to select an intuitive sorting method for the management form with multiple fields. We may want to package a form with multiple fields in groups:

from django.contrib import adminfrom polls.models import Questionclass QuestionAdmin(admin.ModelAdmin):    fieldsets = [        (None,               {‘fields‘: [‘question_text‘]}),        (‘Date information‘, {‘fields‘: [‘pub_date‘]}),    ]admin.site.register(Question, QuestionAdmin)

The first element of each ancestor in the group is the title of the Group. The following figure shows the modified form:

In addition, we can also specify HTML style classes for each group. Django provides a "collapse" class for displaying groups whose initial status is shrinking. It is very useful when there is a long form that is not commonly used.

from django.contrib import adminfrom polls.models import Questionclass QuestionAdmin(admin.ModelAdmin):    fieldsets = [        (None,               {‘fields‘: [‘question_text‘]}),        (‘Date information‘, {‘fields‘: [‘pub_date‘], ‘classes‘: [‘collapse‘]}),    ]

13. Add an associated object

Now we have the question management page, but one question has multiple choice, but the management page is not displayed?

There are two ways to solve this problem: the first is to register choice as you registered question, simply add several lines of code:

from django.contrib import adminfrom polls.models import Choice, Question# ...admin.site.register(Choice)

Now "choice" is an available option on the Django Management page. The "add choice" form is as follows:

In this form, the "Question" field is a drop-down selection box containing all the question in the database. Django knows that the foreign key should be displayed in the <SELECT> box. Of course, there is only one question.

Note that "+" next to "questin" generates this link when an object with a foreign key is associated with another object. When you click "+", a window will pop up to add "add question. If quesiton is added and saved, Django will save it to the database and dynamically add it to the option in the "add choice" form that is currently being viewed.

Note: Adding choice through the above method is very inefficient. It is more efficient to add a batch of choice when creating a question object at the beginning, next, we will try to do this.

Remove choice's call to the Register () method, and then change the registration code of question to the following:

from django.contrib import adminfrom polls.models import Choice, Questionclass ChoiceInline(admin.StackedInline):    model = Choice    extra = 3class QuestionAdmin(admin.ModelAdmin):    fieldsets = [        (None,               {‘fields‘: [‘question_text‘]}),        (‘Date information‘, {‘fields‘: [‘pub_date‘], ‘classes‘: [‘collapse‘]}),    ]    inlines = [ChoiceInline]admin.site.register(Question, QuestionAdmin)

This tells Django that the choice object will be edited on the question management interface. By default, three choice field spaces are provided. Reload the "add question" page to see the effect:

There is a "+ add another choice" button at the bottom of the three choice, which can be used when more needs to be added, to delete a choice slot, click 'x' in the upper-right corner of the corresponding slot '. Note: The three default slots cannot be deleted.

There is also a small problem. To display all associationsChoiceFields of an object occupy a large amount of screen space. Therefore, Django provides a way to display embedded correlated objects in a table.ChoiceinlineChange the statement to the following:

class ChoiceInline(admin.TabularInline):    #...

UsedTabularinlineAfter (insteadStackedinline), The related objects are displayed more compact in table-based format:

Note that there is an additional "Delete ?" When columns are allowed to be saved, the rows that have been saved are removed.

14. Management list on the custom management page

By default, Django displays the results of every object processed by STR. However, sometimes it is better to display the values of each field. To do this, you need to use the list_display management option. This is a tuple containing the field name to be displayed and will be displayed on the modification list page of the object in the form of columns.

class QuestionAdmin(admin.ModelAdmin):    # ...    list_display = (‘question_text‘, ‘pub_date‘,‘was_published_recently‘)

The change list page of question is as follows:

BesidesWas_published_recentlyThis column does not support sorting by method output content. You can click the column title to sort these values. By default, the column title is the method name, the underline is automatically replaced with a space, and each row is output in the form of a string.

Of course, you can also add some attributes to this method (Polls/models. py) to improve the display effect, as shown below:

class Question(models.Model):    # ...    def was_published_recently(self):        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)    was_published_recently.admin_order_field = ‘pub_date‘    was_published_recently.boolean = True    was_published_recently.short_description = ‘Published recently?‘

Edit polls/admin. py again and add a function to improve the question modification list (filter). Add the following content to questionadmin:

list_filter = [‘pub_date‘]

This adds a sidebar for "filtering ".Pub_dateTo filter the content displayed in the Change List:

The type of the field to be filtered depends on the type of the field to be filtered. BecausePub_dateIsDatetimefieldFor example, Django provides the Corresponding filtering options: "Any date," "Today," "last 7 days," "this month," "this year ."

Next, add a search function:

search_fields = [‘question_text‘]

You can see that a search box is added at the top of the modify I list page. Although you can search by any number of fieldsLikeQuery. Please use it properly to maintain database performance. Of course, there are other functions that can be added, not listed one by one.

15. Custom management interface appearance

Obviously, it is unscientific to have "Django administration" on the top of each management page, although it is only a placeholder symbol.

However, using the Django template system is easy to change. The Django management website has the functions of the Django framework. You can use the Django template system to modify the interface.

Custom Project template

Create a Templates folder in the project directory. The template can be stored anywhere in the file system. Django can run on your server as any user, so it can be accessed. However, it is best to develop a good habit of saving template files in projects.

Open the configuration file (mysite/settings. py) and add a template_dirs setting:

TEMPLATE_DIRS = [os.path.join(BASE_DIR, ‘templates‘)]

Create an admin folder with the Templates folder, and then use the default Django management template directory (Django/contrib/admin/templates) CopyAdmin/base_site.htmlTemplate to this folder.

Where is Django's source code? If not found, you can use the following script to find

import syssys.path = sys.path[1:]import djangoprint(django.__path__)

Then, you just need to edit the file and replace {site_header | default: _ ('django adminision')} with the name you think is appropriate. For example: {_ ('polls admin ')}}. This is just an example. In a real project, you may use the Django. contrib. admin. adminsite. site_header attribute to easily customize your own.

This template contains a large amount of text, such:{% Block branding %}And{Title }}.{%And{{Tag is part of the Django template language. When Django is renderedAdmin/base_site.htmlGenerate the final HTML page based on the template language.

Note: by default, Django can manage any template in the website. To override a template, you only needBase_site.htmlThe same way -- copy from the default directory to your custom directory and modify it.

Custom Application Template

IfTemplate_dirsThe default value is null. How does Django find the default website management template? The answer is that by default, Django will automatically search in each application package.Templates/Directory. (Do not forgetDjango. contrib. AdminIs an application ).

Our poll applications are not very complex and do not require custom management templates. However, if it becomes more complex and the standard management template of Django needs to be modified for some functions, it is more wise to modify the application template, rather than modifying the project template. In this way, you can customize templates for any new project, including polls applications, and find the desired custom templates with confidence.

Custom Management Homepage

By default, the homepage is displayed onInstalled_appsAll applications that have registered the management function in and are sorted alphabetically. You may want to make major changes to the page layout. In short, the home page may be the most important page for website management, so it should be easy to use.

The template you need to customize isAdmin/index.html. (Same as before processingAdmin/base_site.html-Copy from the default directory to your custom template directory .) Edit this file and you will seeApp_listTemplate variable. This variable contains every installed Django application. You can use hard coding to link to the Management page of a specific object, instead of using the default template.

Reference: https://docs.djangoproject.com/en/1.7/intro/tutorial02/

Not yet to be continued ....

Django1.7 Learning (III)

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.