[Notes] Django Django Quick Start Section 3: Views and Templates

[Notes] Django Django Quick Start Section 3: Views and Templates

 

Notes on official documents and technology blog , extract key information, and record notes, see the official documentation routines .

Complete official document: Django Documentation 

Recommended blog: Django2.2 Tutorial

 

Django Getting Started official document: Part 3: Views and Templates

table of Contents

1. View

1.1. Define Views

1.2. Configuration URLconf

2. Templates

2.1. Creating a template

2.2. View template call

2.3. Remove Templates hard-coded URLs

3. Add URL namespace name


1. View

Django concept of view is "a kind of pages with the same functions and templates collection", a view is a page, usually provides a specific function, using specific templates.

In Django, and some other content pages are handled by the view. View is actually a simple Python function (called methods of the class based on the view). Django view by selecting the corresponding request URL address comparison.

Django design framework for MVT, the URL the user requested is a view, a rear view of receiving a request for processing, and returns the processing result to the requester.

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

(URLconf More from reference:  the URL of the scheduler )

 

Required the use of two steps view:

  1. Defined view function
  2. Configuring the URLconf (configure routes)

 

1.1. Define Views

  • Python is a view function is defined views.py in.
  • View must have a parameter , usually called the request, the view must return HttpResponse object , HttpResponse the parameter content will be displayed on the browser page.

 

 

1.2. Configuration URLconf

Configuring URL, establishing correspondence between the url address and views. General view views.py file applications under the new folder where a urls.py to configure URL, then urls.py project to import it.

Finding view of the process (to understand)

  1. Requester enter url in the browser address bar,
  2. After the website get request to obtain url information, then write a good and URLconf one by one match ,
  3. If the match is successful then call the corresponding view function , if not all URLconf successful match, a 404 error is returned.
  4. (See examples of official documents, read carefully)

 

A URLconf includes url rules, views :

  • url-defined rules using regular expressions (usage before Django2, after not recommended)
  • Recommended path function after Django2
  • View view function is defined in the views.py.

 

URLconf configuration requires two steps :

  • 1. Definitions In the application URLconf
  • 2. The project included URLconf

note:

The view is not generally applied directly urls.py project configuration, but urls.py configuration in the application directory, and then urls.py project to include come .

 

Shortcuts: render () function

In practical application, load the template, pass parameters, return HttpResponse object is a set of re-used, but the operation, in order to save energy, Django provides a shortcut: render function, in one step! No longer need to import  loaderand  HttpResponse, but from django.shortcutsimported render.

  • render () function of the first parameter is a location request object (the first parameter is a function of view) ,
  • The second parameter is the position of the template .
  • You can also have an optional third argument, a dictionary needs to be passed to the data template contains .
  • Finally render function returns a dictionary data rendered through a template made of encapsulation HttpResponse object .

 

Shortcuts: get_object_or_404 ()

Render the same function as, Django provides get_object_or_404 () method returns to 404. Do not forget to start with Django built-in export modules Shortcutsget_object_or_404()。

  • get_object_or_404()Method Django a position parameter of a model,
  • The back can keep up with any number of keyword arguments, if the object does not exist Http404 error pop up.
  • See get_object_or_404() 

There is also  get_list_or_404() a function of the working principle and  get_object_or_404() the same, except that  get() the function has been replaced by  filter() function. If the list is empty, then it will throw  Http404 an exception.

( Filter is used to model the API function filter query results, which is a list of the result set. And get the result of a query method, and is the difference between a filter and a plurality of!)

 

2. Templates

 In Django, the front-end content definition in the template, and then call the template to view a variety of beautiful, cool effects appeared.

 

2.1. Creating a template

  1. Create a template file
  2. Configuration template directory

 

1.  Create a template file

Template in the project root directory templates  directory, propose to establish a catalog of the same name in each application to place their template file .

The directory structure similar to the following:

项目名
└──...
└── templates
    └── 应用名
    |    ├── 模板1
    |    └── 模板2
    └── 应用名2
        ├── 模板21
        └── 模板22

 

Output variables in the template syntax is as follows, variables may be passed from view over, it may be defined in the template.

{{variable name}}


Write code section in the template syntax is as follows:

%}% {Snippet

 

 

2.  configuration template directory

Find the path set template: Open the configuration file for the project settings.py file, set TEMPLATES the DIRS value

'DIRS': [os.path.join(BASE_DIR, 'templates')],

(Note: the use of stitching, BASE_DIR is a directory of the project)

 

2.2. View template call

View call template is divided into three steps:

  • Find the template : the template file is loaded. For example, to obtain the contents of the template directory html file, get a template object.
    • 用from django.template import loader,loader.get_template() 
  • Defined template context : to pass data to the template file.
    • With from django.template import RequestContext, RequestContext () function  (Django2.x Found failure, given context must be a dict rather than RequestContext .. The reason is that the new version, the context should be dict)
    • Update : a dictionary definition as the context, such as empty dictionary {}
  • Rendering template : get the standard html content.
    • 用template.render(context)

 

View call template have to perform more than three parts, in order to reduce developers to write repeated loading, rendering code, Django provides a shortcut function:  , used to call the template. The method  comprises three parameters:render()render()

  • The first parameter is the request object
  • The second parameter is the file path template
  • The third parameter is a dictionary, represents the transfer of context data to the template

 

2.3. Remove Templates hard-coded URLs

When writing a link in the template, if the link is hard-coded, for code changes very unfavorable.

Hard-coded links and strong coupling, for a project that contains many applications, it is very difficult to modify it.

Just give urls define a name alias , you can use it to solve this problem.

 

As long as the  application.urls  's  url() function by name as a parameter defines the name of the URL of , you can use  {% url %} the tag instead of it:

     比如:<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

Django will be in the application urlsfile lookup  name='detail'url, concrete is the following line:

      path('<int:question_id>/', views.detail, name='detail'),

In this way, url views even change the templates do not have to make changes.

 

3. Add URL namespace name

Django URL name to distinguish between a project with multiple app? How Django knows  what a URL corresponding to the application of labels in the end it? {% url %}

A: The use of namespaces URLconf. Add the namespace root URLconf. Plus  app_name set namespace.

Such as: polls application  polls/urls.py file, add  app_name setting the namespace, i.e. applied in a urlpatterns: APP_NAME = 'polls'

Complete this:

from django.urls import path

from . import views

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

Thus, in a template can be {% URL ' Detail ' question.id%} to {% URL ' polls: Detail ' question.id%} .

<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

Note: urls.py project, when urls.py include application, you can also add namespace ,

如:path('polls/', include('polls.urls', namespace='polls')),

 

-----end-----

Published 50 original articles · won praise 10 · views 6597

Guess you like

Origin blog.csdn.net/qq_23996069/article/details/104696993