Frist Django app-3. View, fristdjango

Source: Internet
Author: User

Frist Django app-3. View, fristdjango

I have already mentioned some usage of models in Django, including orm and operation APIs. Next I will take some simple interfaces to learn view-view in Django. This article mainly introduces the following two aspects:

  • Url ing
  • Request Processing
  • Template File

Url ing and request processing constitute the C-controller in MVC, which involves the url Writing Method (mainly regular expressions) and receives parameters transmitted from the page. In Django, you can use a template for page rendering, so that you can directly use the transmitted data.

Url ing

The previous project completed the polls project. The home page of the polls website displays a list of recent problems. You can also view the details of a problem and further view the results of the investigation. Vote

  • Index: displays the list of recent problems.
  • Detail: view the details of the problem
  • Result: displays the result of a problem.
  • Vote: vote for an answer to the question

The above four functions are used to edit polls/urls, py

from django.conf.urls import urlfrom . import viewsapp_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'),]

Name: name of the url rule, which can be referenced in the template

App_name: defines the url namespace. The namespace is used to prevent name duplication.

Request Processing

Edit polls/views. py

From django. shortcuts import render, get_object_or_404from django. http import HttpResponse, Http404from models import Question # Create your views here. def index (request ):
# Query the latest five Question.-indicates that latest_question_list = Question is sorted in descending order. objects. order_by ('-publ_date') [: 5] context = {'latest _ question_list ': latest_question_list} return render (request, 'lls/index.html', context) def detail (request, request, question_id): question = Queue (Question, pk = question_id) return render (request, 'lls/detail.html ', {'question': question}) def results (request, question_id ): return HttpResponse ("result: question id is % s" % question_id) def vote (request, question_id): return HttpResponse ("vote: question id is % s" % question_id)

Views. py is processed through urls. for the requests distributed by py, for example, in the last vote above, a HttpResponse object is directly returned. In fact, all views are processed to return the HttpResponse object, including when the render method is used.

  • Return HttpResonse
  • Call render to render data to templates and return HttpResponse

Get_object_or_404: gets a Question object and throws an Http404 Exception if it does not exist. This is the optimized code. It was originally used to manually find an object and determine whether the object exists and does not exist before raise Exception, after the improvement, the coupling between the model and view is reduced, so that the view no longer depends on the specific implementation of the model layer to achieve the goal of decoupling.

Template File

Under mysite/polls, create two levels of directory mysite/polls/templates/polls. templates is fixed, and polls is the APP name, create an index.html file in the mysite/polls/templates/pollsdirectory, that is, the template file.

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

Here are some notes:

Templates/polls directory

The settings. py file contains the settings for templates.

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: the BACKEND template engine django. template. backends. django. DjangoTemplates.

DIRS: The template location does not have to be placed in the agreed directory, but it is recommended to put it in the directory of each APP name, avoid Django confusion when multiple apps have the same Template Name

When APP_DIRS is set to true, DjangoTemplates searches for the Template under the app directory, namely, polls/templates/polls.

So we put the above in the default directory

Template syntax

The Djang template contains common html code and template code, such as if-else, for, and dotted syntax (access data. Here we will first introduce some basic things, not to mention html.

  • The template code is surrounded by common {%}, and the syntax is {% url % }.
  • {Data in the template }}
  • {% If %} {% else %} {% endif %}
  • {% For %} {% endfor %}
  • Latest_question_list is views. the parameters passed by py can access data using the dot syntax. supported data formats include value transfer and reference (including list, dic, tuple, object attribute, object method (no other parameters, must have a return value). When using the dot syntax, Django searches for parameters in the order of dictionary, object attribute, object method, and list.

Url namespace

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

In urls. in The py file, app_name is the url namespace by declaring a global variable. In the {% url %} syntax, you can use app_name + name to reference the url, such as 'polls. detail 'indicates which url match is used. question_id is the parameter passed to the url match.

 

Summary

In addition to the basic knowledge of Django, I also learned (worship) the elaborate design of Django and loose coupling.

  • Django encapsulates the Http404 exception when retrieving a single object and decouples the model and view
  • You do not need to hard-encode the url in the template file using the {% url %} syntax to decouple the url ing.

 

 

Complete code

Http://pan.baidu.com/s/1kUFv5lH

 

Related Article

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.