Create a polling site with Django (ii)

Source: Internet
Author: User

Create your first Django project, part Two

This article continues from the end of the first part (ZH). In this section we will continue to write the Web voting app and focus on the automatically generated administration page (admin site) provided by Django.

Design philosophy

Creating a Management page for your employees and customers to add, modify, and delete site content is tedious work and does not require much creativity. For these reasons, Django provides the ability to fully automate the creation of management interfaces for the model.

Django is generated during the development of a news site that is completely detached from a public page and a content Publisher page. Site managers use the management system to add news, events, and sports newsletters, which are displayed on public pages. Django solves this problem by creating a unified content editing interface for site managers.

The management interface is not for visitors to the site, but for managers.

Create an Administrator account

First, we have to create a user who can log on to the admin page. Please run the following command:

$ python manage.py createsuperuser

Enter the name of the user you want to use, and then enter.

Username: admin

You will then be prompted to enter your email address:

address: [email protected].com

The last step is to enter a password. You will be asked to enter the password two times, the second time is to confirm that the first input is really the password you want.

********Password(again): ********Superuser created successfully.
Start the server for development

The Django Admin interface is enabled by default. Let's start the development server and see what it looks like.

Call the command that runs the development server again in the first part of the tutorial (ZH):

$ python manage.py runserver

Now, open your browser and go to the "/admin/" directory of your local domain name, such as "Http://127.0.0.1:8000/admin". You should see the Administrator login screen:

Because the translation function is on by default, the login screen may use your language, depending on your browser settings and whether Django has been translated into your language.

Not the same as what you saw?

If in this step, you see not the interface shown, but an error page, just like this:

ImportError at /admin/cannot import name patterns...

Then you may have used a Django version that does not match the tutorial. You can switch to the previous version of the tutorial, or choose to upgrade Django to a newer version.

Go to Administration page

Now, try logging in using the superuser you created in the previous step. You will then see the index page of the Django Administration page:

You'll see several editable content: groups and users. They are provided by Django.contrib.auth , which is a validation framework that is developed by Django.

Add a voting app to the Administration page

But where are our voting applications? It is not displayed in the index page.

Just one thing to do: we have to tell the admin page that the problem (Question) object needs to be managed. Open the polls/admin.py file and edit it to the following:

# polls/admin.pyfrom django.contrib import adminfrom .models import Questionadmin.site.register(Question)
Experience the convenient management function

Now we have registered the problem (Question) class with the Administration page. Django knows it should be displayed in the index page:

Click "Question". You now see a list of the problem (Question) objects. This interface will display all the problems in the database (Question) object, you can choose one to modify. Now we have the "What's up" that we created in the previous section? Problem.

Click "What's Up?" To edit this problem (Question) object:

There are some things to note:

    • This form is automatically generated from the problem (Question) model.
    • The different field types ( datetime fields (Datetimefield), character fields (Charfield)) generate the corresponding HTML input controls. Each type of field knows how they will show themselves on the admin page.
    • Each datetime field (Datetimefield) has a shortcut button written by JavaScript. The date has a shortcut button and a popup calendar interface that goes to today. Time has a shortcut button set to now and a handy pop-up list that lists common times.

Several options are available at the bottom of the page:

    • Save-Save changes and return to the list of objects.
    • Save and continue editing (save and continue editing)-Save the changes and reload the current object's modify interface.
    • Save and add another-save changes, then add a new empty object and load the Modify interface.
    • Delete-Displays a confirmation delete page.

If the "date Published" displayed is inconsistent with the time you created them in the first part of the tutorial, this means that you may not have the correct settings time_zone. Change the settings and reload the page to see if the correct values are displayed.

Change the release date (Date Published) by clicking the Today and now buttons. Then click the "Save and continue editing (save and add another)" button. Then click the History button in the upper-right corner. You will see a page listing all the changes made to the current object through the Django Admin page, which lists the timestamp and the user name for the modification operation:

Custom Management Forms

Take a few minutes to marvel at it. You don't have to write any code to have the management interface of the miracle it. By using the admin.site.register (Question) registration Problem (Question) class, Django can construct a default form style. Typically, you'll want to customize the style and function of your form. You can do this by adding some options when registering the object.

To see how to change the order of the fields in the form. Replace admin.site.register (Question) with the following code:

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

When you want to change some of the options on the Administration page, the steps are typically: Create a Model Admin object (the Models administrator objects) and pass it as the second argument to the admin.site.register () function.

The code above causes the release date (Publication date) to appear before the question description (Question text) field.

If you have only two fields, you don't feel anything, but when the form has more than 10 fields, choosing an intuitive order is a way to improve the user experience details.

If you really have more than 10 fields, you might want to group them into multiple field sets (FieldSets):

# polls/admin.pyfrom django.contrib import adminfrom .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 a tuple in the FieldSets list is the grouping name. Here's what the form looks like now:

You are free to assign an HTML Class to each group. Django provides   collapse (collapse)   class, the groupings that belong to this class will be initialized to collapsed form. This feature is useful if you have a long form and some fields are not commonly used.

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

To add an associated object

Now we can manage the problem (Question). But each problem (Question) has multiple options (Choices), and there is no Choices in the admin page.

But it's going to be right away.

There are two ways to solve this problem. The first is to register the option (Choices) Like registration issues (Question). This is simple:

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

Now, there's an "option (Choices)" In the Django admin page. The "Add Choices" form looks like this:

In this form, the "Problem (Question)" field is represented as a selection box that contains the problem (Question) that is stored in all the databases. Django knows that the foreign key should be represented as a selection box. Now, there is only one problem in the list (question).

The Add another button next to question (Question) is also worth noting. Each foreign key field will have this button. When you click on it, a window pops up with the Add question form. If you use it to add a problem (Question) and click "Save", Django stores the problem (Question) object in the database and dynamically adds it to the problem (Question) selection box in the previous "Add Options" form.

However, to be honest, it is very inefficient to add options (Choices) to the database. It would be nice if you could add a few options to it when you added a question (Question). To see how this can be achieved:

Delete the Register () statement for the option (Choices) model, and then edit the registration code for the problem (Question) :

# polls/admin.pyFrom Django.contribImport Adminfrom. Models import Choice, Question class choiceinline  (admin. Stackedinline): Model = Choice extra = 3 class questionadmin (admin. Modeladmin): FieldSets = [(none, { ' Fields ': [ ' Date information ', { Fields ': [ ' pub_date '],  ' classes ': [ ' Collapse '}),] inlines = [Choiceinline]admin.site.register (Question, questionadmin)     

The added code will tell Django that the "Choice (option) object will be edited in the management interface of the problem (Question) . 3 option fields are displayed by default for editing. ”

Reopen the Add Question page:

Now there are 3 units that can add related options (choices)--"3" is defined by extra in the code--and every time you enter a modified interface for an already created object, there will always be an additional three units that allow you to add options.

At the bottom of the three Add option units is a "add an option (Choices)" button. But when you click on it, a unit that adds an option is added above. If you want to delete the added unit, you can click the X in the upper right corner of the cell. Please note: You cannot remove the initial three units. The following image shows the effect of a new unit:

There's a little problem. Showing all the relevant options (Choices) units is too much of a screen space. For this reason, Django provides a tabular view: you just have to change the definition of choiceinline :

By using tabularinline (instead of stackedinline), the related objects will be displayed in a more compact, tabular format:

More out of the "delete?" The (delete?) column can be used to delete data added through the Add another Choices button, although they are already stored.

Custom Object List

Now that the Django Object modification page is great, let's tweak the object list page-that is, the page that displays all the problem (Question) objects.

At the moment it's like this:

By default, Django uses the str () method to display objects. But sometimes it can be useful if we show some other fields. To do this, we can use the list_display option, which is a tuple of field names that need to be displayed, which will appear in the list as additional columns.

# polls/admin.pyclass QuestionAdmin(admin.ModelAdmin): # ... list_display = (‘question_text‘, ‘pub_date‘)

To facilitate retrieval, we also added the was_published_recently method that we customized in the first part of the tutorial:

# polls/admin.pyclass QuestionAdmin(admin.ModelAdmin): # ... list_display = (‘question_text‘, ‘pub_date‘, ‘was_published_recently‘)

Now, the list of objects for the problem (Question) is as follows:

By clicking on the table header, you can have the list sorted by the selected attribute-except for the was_published_recently function, because Django does not support sorting by the output of a randomly defined method. The column name of the column in which the was_published_recently method is used defaults to the method name (the underscore is replaced by a space) and the displayed value is the string form of the corresponding method return value.

You can extend the functionality by adding properties to the method to see the following example:

# polls/models.pyclass 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?‘

For more method options, see the Documentation:list_display.

Edit the polls/admin.py file again. We want to add a new feature to the list of objects in question (Question): Filter objects by list_filter . Add the following to questionadmin :

list_filter = [‘pub_date‘]

The purpose of the above code is to add a "quick filter" sidebar to the list of objects, which can be selected by the pub_date field (Question).

The type of filtering depends on which field you want to filter. Because pub_date is a datetime field (Datetimefield), Django automatically provides the appropriate filtering method: "Anytime (any date)", "Today", " Over the past 7 days (past 7 day), "This month", "this year".

This function is done, let's add some search functions:

search_fields = [‘question_text‘]

This will add a search box at the top of the object list. Django searches the question_text field when someone types something. You can search for as many fields as you want-although the search process uses the LIKE keyword in a database query statement, limiting the number of search results will make the database search easier.

By default, Django is one page per 100 objects.

Object list paging, search boxes, filters, grouping by time, and sorting by table header can be combined to work together perfectly.

Customize Manage Page Styles

Obviously, there's a "Django administration" in the upper left corner that looks ridiculous, but it's just a placeholder text.

You can easily change it-by using the Django templating system. The Django Admin page is provided by Django itself, and its interface uses the Django template system.

Customizing project templates

Create a Templates directory in your project folder (the folder wheremanage.py is located). Templates can be placed anywhere that Django has access. (Django and the user who performed the start server operation have the same permissions.) However, putting templates in the project directory is a convention and it's good to follow it.

Open the settings file (remember, it is mysite/settings.py) and add the DIRS option to the TEMPLATES settings:

# mysite/settings.pyTEMPLATES = [    {        ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘, ‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)], ‘APP_DIRS‘: True, ‘OPTIONS‘: { ‘context_processors‘: [ ‘django.template.context_processors.debug‘, ‘django.template.context_processors.request‘, ‘django.contrib.auth.context_processors.auth‘, ‘django.contrib.messages.context_processors.messages‘, ], }, },]

DIRS is a collection of directories on the file system that will be searched when loading the Django template.

Now create the admin directory in templates and then from the default Django Admin page template directory in the Django Code directory (django/contirb/admin/templates ), copy the admin/base_site.html template to the new directory.

Where is the Django code directory?

If you don't know where the Django code directory is, try these commands:

$ python -c "import syssys.path = sys.path[1:]import djangoprint(django.__path__)"

Then, just replace {{site_header|default:_ (' Django Administration ')}}(including curly braces) with the characters you want. You should edit it to look like this:

 {%  Block branding%}<h1 id= "site-name" ><a href= "{%" Span class= "Hljs-keyword" >url ' Admin:index '%} " >polls administration</a></< Span class= "Hljs-title" >h1>{% endblock%}   

We just use this example to teach you how to cover templates. In a real project, it would be easier to use the Django.contrib.admin.AdminSite.site_header property to set a custom caption.

The template file contains a lot of text like {% block branding%} and {{title}} . {% and {{ tags are part of the Django template language.} When Django renders admin/base_site.html , the template language is executed, and the result is an HTML document. If you don't understand the template right now, don't worry, the third part of the tutorial will cover the template language in more detail.

All default templates for the Django Admin interface can be overwritten. If you want to overwrite them, just like you overwrite base_site.html , copy the original template to your directory and modify it.

Customizing app Templates

A keen reader will think: if the DIRS directory maintains the default null value, how does Django know where to find the default template? The answer is, because app_dirs is set to True, Django automatically searches the templates/ subdirectories under each app directory as the last alternative. (Don't forget,Django.contrib.admin is an app too)

Our voting application is not too complicated and does not require a custom administration page. But if it's slowly becoming a complex application, modifying the template of the Django Admin page to add some functionality would be a smarter choice than the project template . In this way, you can use the voting app in a new project and make sure it can also find the custom templates you need.

Check the template load documentation for details on how Django looks for templates.

Custom Administration Page Index page

Similar to. You might want to customize the style of the Django Admin Page index page.

By default, the index page displays all apps in Install_apps that have been registered with admin in alphabetical order. You might want to make some big changes to the interface. Remember, however, that the index page is probably the most important one on many management pages, and it needs to be simple and easy to use,

What you need to customize is admin/index.html. (similar to the steps above for customizing admin/base_site.html -Copying a copy from the default template directory to a custom template directory) Open this file and you'll see that it uses a variable called app_list . This variable contains all the activated Django apps. In addition to using this variable, you can also use any method that you think is appropriate to make the address of the management page of a particular object hard-made in the template. Again, if you don't understand the template right now, don't worry, the third part of the tutorial will cover the template language in more detail.

Once you're familiar with the administration page, you can start reading the third part of the tutorial (ZH) and start developing the public interface for the voting app.

Create a polling site with Django (ii)

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.