picture

Last time I introduced it to you  Django   Model of , The database can be operated through the model , So you can change the content of the page , That's the question , Can we only configure the model by manually editing the model file ? Of course not. ,Django   Provides us with powerful tools , It can automatically create background management interface according to the model . The management interface is not for visitors to the site , It's for site managers . With this function , Site managers can easily use the management system to operate the data .

function Django Admin

First of all, we created last time TestProject project , And we have created in this project polls application , And we created two models:Question and Choice. The code is as follows :

# polls/models.py
from django.db import models
class Question(models.Model):    question_text = models.CharField(max_length=200)    pub_date = models.DateTimeField(' Release date ')

class Choice(models.Model):    question = models.ForeignKey(Question, on_delete=models.CASCADE)    choice_text = models.CharField(max_length=200)    votes = models.IntegerField(default=0)

Next, let's move on to this project and make changes , And run Django Admin Management tools .

Modify the configuration file

In the project TestProject In the directory settings.py file , Open editor INSTALLED_APPS And increase django.contrib.admin And other related items ,django.contrib It's a huge set of features , It is Django Part of the basic code , and Django The automation tool is django.contrib Part of . The results are as follows :

# TestProject/settings.py
INSTALLED_APPS = [    'polls.apps.PollsConfig',    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',]

Configure access path

On top of that , There is one urls.py file , Access path to configure administrative tools . Of course, usually when we build a project, we do it in urls.py Automatically set the , We just need to get rid of the comments , Please look at the following code :

# TestProject/settings.py
from django.contrib import adminfrom django.urls import path, include
urlpatterns = [    path('polls/', include('polls.urls')),    path('admin/', admin.site.urls),  # To configure /admin route ]

Okay , It's all configured , Now let's run Django Management tools , Same as before , First by order python manage.py runserver 127.0.0.1:8080 Start a local server, And then by visiting URL http://127.0.0.1:8080/admin You can jump to the management tools landing page , As shown in the figure below :

 picture land

You've seen the landing page , Next, we need to enter the user name and password to log in .

Initialize Super Administrator

Django admin The user of the management tool needs to initialize it with a command , Back to project root , perform python manage.py createsuperuser, Then complete the initialization according to the command prompt , The operation results are shown in the figure below :

 picture initialization

User name password initialization complete , We can enter... On the landing page , Then you can log in to the management tools page , Here's the picture :

 picture Home page

Management applications

After successful landing on it , We only see the management content related to users and groups on the management page , This is the application of the management tool , I don't see what we created before polls application , Next, let's introduce how to use Django admin How management tools manage our application model . The first change polls Under the application of admin.py file , Add the following code :

# polls/admin.py
from django.contrib import admin# introduce polls Under the application of modelsfrom polls.models import Question,Choice
# Register two models admin.site.register(Question)admin.site.register(Choice)

Exit after saving , Then refresh the main page , You can see our polls The model management interface of the application , As shown in the figure below :

 picture

Then we can be right polls Using data to operate , Click on Questions Add button corresponding to the model , Jump to the new data page , And fill in a question description and set the release date , Here's the picture :

 picture

Click Save to exit to the list page , And prompt that the operation is successful , And then we use the polling questions that we've configured before URL http://127.0.0.1:8080/polls/query The query , You'll find the new voting question , The query results are shown in the following figure :

 picture

Is it fast and convenient ? Of course, in addition to adding , You can also modify and delete the data , You can click the corresponding record under the name of the model to be operated in the list , Then jump to the modify and delete page , As shown in the figure below :

 picture These operations are relatively simple , I won't go into details here , But here's the thing :
  1. This form is from the question Question Automatically generated in the model
  2. Different field types ( datetime field DateTimeField 、 Character fields CharField) I'm going to generate the corresponding HTML Input control . Each type of field knows how to display itself in the administration page .
  3. Every date time field DateTimeField There are JavaScript Write shortcut button . The date has a shortcut button to go to today and a pop-up calendar interface . Time has a shortcut button to set to now and a convenient pop-up list of commonly used times .

In addition, there are several options at the bottom of the page :

  • preservation : Save change , Then return to the list of objects .
  • Save and continue editing : Save change , Then reload the modification interface of the current object .
  • Save and add : Save change , Then add a new empty object and load the modify interface .
  • Delete : Show a confirmation delete page .

summary

This article introduces Django Admin Management tools , It can be configured simply through the application model , Generate the corresponding background data management page , Through this management page , We can easily manage data . Except for the simple model, of course , It can also manage complex models , And you can customize forms and styles , Interested friends can be more in-depth study .

Reference resources

Django Chinese official website :https://docs.djangoproject.com/zh-hans/2.2

Sample code :https://github.com/JustDoPython/python-100-day


Series articles


The first 122 God :Flask unit testing

The first 121 God : Decision trees for machine learning
from 0 Study Python 0 - 120 Summary of the grand collection