django learning - management interface, view

django Management Interface

design background

For your employees or customers generate a user to add, modify, and delete the contents of the background is a lack of creativity and tedious work. Therefore, django fully automatically create backend interfaces according to the model.

 

django produced in the process of developing a public page and content publishers to completely separate pages of news sites.

Site managers use the management system to add news, Time and Sports newsletters, etc. These added content is displayed on the public page. django solves this problem by creating a unified content editing interface for the site managers.

 

Management interface is not for site visitors, but for managers to prepare.

 

Create an administrator account

First, we have to be able to create a login user management page. Run the following command:

py -3 manage.py createsuperuser

D:\django\mysite>py -3 manage.py createsuperuser

#Enter your user name

Username (leave blank to use 'lenovo'): admin

Enter your e-#

Email address: [email protected]

#enter password

Password:

Password (again):

The password is too similar to the username.

This password is too short. It must contain at least 8 characters.

This password is too common.

Bypass password validation and create user anyway? [y/N]: y

 

Start the development server

django admin page is enabled by default. Let us enable the development server, look at it in the end is what.

If the development server is not started, start it with the following command:

python manage.py runserver

Browser access http://127.0.0.1:8000/admin/ , go to the local domain name "/ admin /" directory, you will see the administrator login screen:

 

 

 

django translation feature is enabled by default, so the login screen may use the browser's language, depending on the browser settings and django if you have the translation language.

 

Admin page to enter the site

Now, try to log in using a superuser you created in the previous step. Then you will see the index page of django management page:

 

You will see several editable content: groups and users. They are provided by django.contrib.auth, which is authentication framework django development.

 

 

Added to the voting application management page

But our poll application where is it? It did not appear in the index pages

Just do one thing: we have to tell management page, the problem Question objects need to be managed. Development polls / admin.py file, edit it to this:

polls/admin.py:

 

from django.contrib import admin

# Register your models here.

from .models import Question

admin.site.register(Question)

 

 

Experience convenient management features

Now we registered the issue Question class to manage the page. django know it should be displayed on the index page in:

 

 

 

Click "Question". Now see the problem "Question" list of objects "change list". This screen displays all the database objects Queston problems, you can select one to modify. Here now we have created in the previous section "What's new?" Question.

 

 

 

Click on "What's new?" To edit this question (Question) Object:

 

 

 

Precautions:

1) When this form is automatically generated from the model problem Question

2) field types (time field DateTimeField, as CharField character field) is generated corresponding HTML input controls. Each type of field knows how they show themselves in the management page.

3) each date time field DateTimeField are written in JavaScript shortcut buttons. Go to date have today (Today) shortcut button and a pop-up calendar interface. Set time there now (Now) shortcut buttons and a convenient pop-up list of commonly used time listed.

 

Bottom of the page offers several options

1) Save (Save) - save your changes, and then returns a list of objects

2) Save and continue editing (Save and continue editing) - to save the changes, and then reload modify the interface of the current object.

3) Save and add (Save and add another) - to save the changes, and then add a new empty object and load the modified interface

4) Delete (Delete) - Displays a delete confirmation page

 

If you see "Date (Date Published)" and you created them time inconsistency, which means you may not have the right to set the time zone (TIME_ZONE). Change settings, then reload the page to see whether the correct value.

 

By clicking on the "Today (Today)" and "now (Now)" button to change the "release date (Date Published)". Then click "Save and continue editing (Save and add another)" button. Then click on the top right corner of the "History (History)" button. You will see a list of all the current page objects by changing the django admin page, which lists the time stamps and modify operations Username:

 

 

 

 

view

Django conceptual view of a [class is set has the same function and the page template].

For example, in a blog application, you might create the following several views:

1) blog home - showcase several recent content.

2) the contents of the "Details" page - detailed display an item

3) on an annual basis archive page - to show the contents of the selected month in the days to create.

4) in days archive page - to show all the contents of the selected days of creation

Comment operable in response to a content of 5 -) processor reviews

 

In our poll application, we need the following several views:

1) issue index page - showcase several recent poll question

2) Issue Details page - shows a problem with the results of voting and non-options class table

3) question results page - shows the results of a vote

Operation of a particular voting options for responding to the user for a problem --4) Voting processor

 

In django, the web page and other content are derived from view.

Each view appears as a simple python function (or method, if it is, then in view of the class-based Lane).

django will be based on the URL requested by the user to choose which view to use (more accurately, is based on the part of the URL after the domain name).

 

In the process you access the Internet, it is likely seen URL like this:

"ME2 / Sites / dirmod.sap? Sid = & type = gen & mod = Core + Pages & gid = A6CD123KJUHJ213". Do not worry, django in the URL rule more elegant than this!

 

A URL schema defines some basic format of the URL

- For example: / newsarchive / <year> / <month> /

In order to associate the URL and view, django using 'URLconfs' configured. URLconf URL patterns mapped to the view.

Such as: mysite / urls.py:

 

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]
Be practicing URL dispatcher: https://docs.djangoproject.com/zh-hans/2.1/topics/http/urls/

 

Write more views

Now we add to the polls / views.py in more views that there are some differences, because they receive parameters:

 

polls/views.py:

 

def detail(request, question_id):
    return HttpResponse("You're lokking at question %s." % requestion_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

 

We add these new views into polls.urls module, as long as adding a few url () (alias re_path function) function call can:

The view function module added to polls.urls

polls/urls.py:

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex:/pools/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

 

Browser access to "/ polls / 14 /", django will run the detail () method and demonstrate problem ID you provide in the URL.

 

 

Access to "/ polls / 34 / vote /" and "/ polls / 14 / vote /", you will see the results and voting pages for temporary placeholder

 

 

 

When someone requests a page of your site, such as "/ polls / 14 /", django module will be loaded mysite.urls

Because it is set in the configuration items ROOT_URLCONF in:

settings.py:

ROOT_URLCONF = 'mysite.urls'

mysite/urls.py:
urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

 

polls/urls.py:

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex:/pools/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

 

Then look for django called urlpatterns variable and in order to match the regular expression. Find matches 'polls /', which cut off the text ( "polls /") matching the remaining text - "14 /" sent to "polls.urls" URLconf for further processing.

URLconf refers polls.urls

 

url view matching process

The first sequence is matched in ROOT_URLCONF settings.py variable ( 'mysite.urls' points to the file to find the variable urlpatterns urls), in order to match path urlpatterns variable () route parameter (the function 'polls /' ) , matching after the, matched to the text ( 'polls /' - part of the path) cut off, the remaining text ('14 / '), to the path () function specified in the URLconf (polls.urls) to match the view function, where the remainder of the text "14 /" to match '<int: question_id> /' , so that the call detail in the following form django ():

detail(request=<HttpRequest object>, question_id=14)

 

polls / views.py: detail function definitions:

def detail(request, question_id):
    return HttpResponse("You're lokking at question %s." % question_id)

 

question_id = 14 a <int: question_id> Generated. Angle brackets "capture" part of this URL, keyword parameters and transmitted in the form of the function to the view. The character string: question_id> section will be used to define the variable names are pattern matching , pattern here is urlpattern row in a matching code, int: a converter is , determines what variables should match this type part of the URL path.

 

For each URL add unnecessary things, such as .html, it is not necessary. If you have to, then you can also:

path(‘polls/latest.html’, views.index),

 

But this is not recommended, too low a

 

Write a truly useful view

Each view must do two things:

HttpResponse returns a requested object comprises a content page, or throw an exception, such Http404.

As you want to be doing, whatever you want.

 

Your view can read records from the database, you can use a template engine (such as django comes, or other third party), you can generate a PDF file, you can output a XML, create a ZIP file, you can do anything you want to do, use any python library you want to use.

 

django requires only returns a HttpResponse, or throw an exception

 

Because django comes with a database API is very convenient, we learned earlier, so we try to use it in the view.

In index () function in inserting some new content, we can show the database last five polling questions to sort of release date, separated by spaces:

from django.shortcuts import render

# Create your views here.

from django.http import HttpResponse

from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    output = ', '.join([q.question_text for q in latest_question_list])
    return HttpResponse(output)

 

Other view function unchanged (detail, results, vote)

 

To demonstrate, we add six questions:

 

 

 

View data in the database

 

 

 

Browser access http://127.0.0.1:8000/polls/ , triggering index view function:

 

 

 

There is a problem: the design of the page write died in code view function inside. If you want to change the look of the page, you need to edit python on behalf of it. So let us use django template system, just create a view, you can design a page separate from the code.

Use django template system

First, create a templates directory in your polls project. django will find the template files in this directory.

 

Your project TEMPLATES configuration items describe how to load and render a django template. The default settings file set DjangoTemplates back-end, and APP_DIRS settings become True . This option will let DjangoTemplates find "templates" subdirectory for each INSTALLED_APPS folder.

 

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',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

 

In the templates in the directory you just created, and then create a directory polls, which then create a new file index.html. In other words, the path to your template file should be polls / templates / polls / index.html. Because django can find the corresponding app_directories , so you only need to use polls / index.html you can refer to this template up.

 

Template namespace

Although we can now template file directly in the polls / templates file (rather than re-establish a subfolder polls), but this is not very good. django will select the first matching template file, if you have a template file and a template file is just another application of the same name, django is no way to distinguish between them. We need help choosing the right django template, the easiest way is to put them into words in the namespace, that is, these templates and their application into a sub-folder of the same name.

 

So we in the templates folder, create a new application with the same name of the folder "polls", then create an index.html file in the subfolder: polls / templates / polls / index.hmtl

 

Enter the following code template index.html

 

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>    
{% endif %}

 

Then, let's update polls / views.py in the index view template to use:

View function using templates:

polls/view.py:

 

from django.http import HttpResponse
from django.template import loader
from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))

 

Context:

Action of the code is loaded polls / index.html template file, and passing it to a context (context). The context is a dictionary mapping template variables within it as python objects.

 

Here is a context dictionary by template.render when rendering templates () method of the context and the request object passed to the template file in the template file, in the context of rendering objects

Trigger View function, rendering the template again

Browser to access the "polls /", you will see an unordered list, a list of voting issues before we added a link to the details page of this vote.

 

click the link:

 

 

 

Shortcut function: render ()

 

"Loading template, populate a context, and then returns generated by it HttpResponse object", it is a very common operation flow.

So django provides a quick function, we use it to rewrite the index () view:

 

polls/views.py

 

from django.shortcuts import render
from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

 

Note that we no longer need to import loader and HttpResponse, but if you have other functions (such as details, results and vote) need to use it, then you need to keep the import HttpResponse

 

Start the server again, access 127.0.0.1:8000/polls/, normal access

 

 

 

render () function is the first parameter of the request object request, the template file name as a second parameter, the third parameter is an optional form of a dictionary object. render () function returns the template file based on the context HttpResponse object rendering parameters obtained.

 

Throw a 404 error

Now, we have to deal with voting details view - it displays the specified voting issue title. The following is the code view:

 

polls/views.py:

 

from django.shortcuts import render
from .models import Question
from django.http import Http404

def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})

 

Here is a new principle, if the designation of the corresponding ID is not a problem, this view will throw a Http404 exception.

 

We discuss later what you need to enter in the polls / detail.html years, but if you want to try the above code is working properly, you can temporarily put this input into the next, so you will be able to test.

polls/templates/polls/detail.html:

 

{{ question }}

 

Access a non-existent request_id: http://127.0.0.1:8000/polls/10/

 

 

 

 

 

 

Shortcut function: get_object_or_404 ()

 

Attempt to acquire an object with get () function, if there is no error thrown Http404 is a common process.

django also provides a fast function, the following details are modified Detail () view code:

 

polls/views.py:

 

from django.shortcuts import get_object_or_404, render
from .models import Question

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

 

Get_object_or_404 first parameter () is a model-based method, the second parameter may be any number that can be transferred to the corresponding model class manager's get () method, finding out if the digital object will Http404 reported error

 

Design philosophy:

Why do we use an auxiliary function get_object_or_404 () rather than trying to capture ObjectDoesNotExist abnormal it? Also, why does not directly model API throw ObjectDoesNotExist but throw Http404 it?

 

Because it would increase the coupling of the model and view layers. One of the most important ideological guidance django design is to guarantee loose coupling. Some controlled coupling will be included in django.shortcuts module.

 

There get_list_or_404 () function, working principle and get_object_or_404 (), except get () function is replaced by a filter () function. If the table is empty, then the class will throw an exception Http404.

 

Guess you like

Origin www.cnblogs.com/xiaxiaoxu/p/11665875.html