Some of the uses of model in Django, including ORM, and the API for operations, are described in the previous section, followed by a simple interface to learn about view in View--django. This article mainly introduces the following two aspects:
- URL mapping
- Request Processing
- Template file
URL mapping and request processing together form the C--controller in MVC, which involves the way the URL is written (mostly regular expressions), and the parameters that the page passes over are received. In Django, you can use template for page rendering, which allows you to use the data that is passed in directly.
URL mapping
This is followed by an engineering improvement polls project, the polls website home page shows a list of recent issues, and you can view the details of an issue to see the results of the survey. To vote
- Index: Displays a list of recent issues
- Detail: View survey Question Details
- Result: Displays the results of a problem
- Vote: Vote on an answer to a question
The above four functions we use four pages, edit polls/urls,py
fromDjango.conf.urlsImportURL from.ImportViewsapp_name='polls'Urlpatterns=[url (r'^$', Views.index, name ='Index'), url (r'^(? p<question_id>[0-9]+)/detail/$', Views.detail, name ='Detail'), url (r'^(? p<question_id>[0-9]+)/results/$', views.results, name ='Results'), url (r'^(? p<question_id>[0-9]+)/vote/$', views.vote, name ='vote'),]
The name of the Name:url rule, which can be referenced in the template
App_name: Defines the namespace of the URL, the role of the namespace is to prevent name names
Request Processing
Edit polls/views.py
fromDjango.shortcutsImportRender, get_object_or_404 fromDjango.httpImportHttpResponse, Http404 fromModelsImportQuestion#Create your views here.defIndex (Request):
# Query the latest five question,-to indicate descending order latest_question_list= Question.objects.order_by ('-publ_date') [: 5] Context= {'latest_question_list': Latest_question_list}returnRender (Request,'polls/index.html', context)defdetail (Request, question_id): Question= get_object_or_404 (Question, pk=question_id)returnRender (Request,'polls/detail.html', {'question': Question})defresults (Request, question_id):returnHttpResponse ("result:question ID is%s"%question_id)defvote (Request, question_id):returnHttpResponse ("vote:question ID is%s"% question_id)
views.py processing the request through urls.py, such as the last vote above, it is very simple to directly return a HttpResponse object, in fact, all views processing is to return the HttpResponse object, including when using the Render method
- return directly to Httpresonse
- Render data to templates and return HttpResponse by calling Render
get_object_or_404: Get a Question object, if not throw Http404 Exception, this is the optimized code, it is to manually find an object yourself, judge whether the object exists, does not exist again raise Exception, the improvement reduces the coupling between the model and the view, so that the view no longer relies on the concrete implementation of the model layer to achieve decoupling.
Template file
Create a new Level two directory under Mysite/polls mysite/polls/templates/polls,templates is fixed, polls is the app name, and then mysite/polls/templates/ Create a new index.html file in the polls directory-the template file
if latest_question_list%} <ul> {for in latest_question _list%} <li><a href="{% url ' polls.detail ' question.id%}"> {{Question.question_text}}</a></li> {% endfor%} </ul>{ else %} <p>no polls is available.</p>{% endif%}
Here are a few things to explain first:
Templates/polls Directory
There's a configuration about templates in settings.py.
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', ], }, },]
Backend: Back end template engine django.template.backends.django.DjangoTemplates
DIRS: The location of the template is not necessarily placed in the agreed directory, but it is recommended to put in the directory of each app name, to avoid multiple apps under the circumstances of the template name is the same when Django is not clear
App_dirs: True when djangotemplates searches for templates in the directory where the app is located polls/templates/polls
So we put it in the default directory.
Template syntax
The Djang template contains common HTML code and template code, such as if-else,for,dotted syntax (Access data). Here first introduce some basic, about HTML not much to say.
- The template code is surrounded by normal {percent-percent}, as well as {%url%} syntax
- {{data in template}}
- {%if%} {%else%} {%endif%}
- {%for%} {%endfor%}
- Latest_question_ The list is passed to views.py parameters, you can use point syntax to access the data, the supported data format has value to pass and reference (including: List,dic,tuple, Object Properties, Object methods (no other parameters, must have a return value)), using point syntax, the order of Django search parameters is: Dictionary, object genus Sex, object methods, List
URL namespaces
<li><a href="{% url ' polls.detail ' question.id%}">{{Question.question_text} }</a></li>
In the urls.py file, by declaring a global variable app_name is the namespace of the URL, you can refer to the URL in {%url%} syntax using app_name+name, such as ' polls.detail ' to indicate which URL match to use, question_id parameters that are passed to URL matching
Summarize
In addition to learning the basics of Django, we also learned to (worship) Django's ingenious design, loosely coupled
- Django encapsulates the Http404 exception when acquiring a single object, decoupling the model and view
- Using the {%url%} syntax does not require the URL to be hardcoded in the template file to achieve the purpose of decoupling the URL mapping
Full code
Http://pan.baidu.com/s/1kUFv5lH
Frist Django app-III, View