Python 3+djanjo 2.0.7 Simple Learning (iii)--django view

Source: Internet
Author: User

1. Concept

The concept of a view in Django is a "collection of Web pages with the same functionality and template." For example, in a blog app, you might create several views like this:

    • Blog Home--show the latest several things.
    • Content "Details" page--detailed display of a content.
    • Archive page in years-displays the content created for each month in the selected year.
    • Archive page in months-Displays the content created each day of the selected month.
    • Archive page in days-displays all content created in the selected days.
    • Comment processor--used to respond to an action that adds a comment to a content.

In our voting application, we need the following views:

    • Question Index page--shows several recent polling questions.
    • Question Detail Page-a list of questions and options that show a poll and no results.
    • Problem results page-show the results of a poll.
    • Voting processor--an action that responds to a user voting for a specific option for a problem.

In Django, Web pages and other content are derived from the view. Each view is represented as a simple Python function (or method, if it is in a class-based view). Django will choose which view to use based on the URL requested by the user (more precisely, according to the part after the domain name in the URL)

To correlate URLs with views, Django uses ' Urlconfs ' to configure them. URLconf Map the URL pattern to the view.

2. Add a view:
votes/views.py

fromDjango.shortcutsImportRender,httpresponse#Create your views here.defIndex (Request):returnHttpResponse ("Hello world! ")defDetail (request,question_id):returnHttpResponse ("You ' re looking at question%s."%question_id)defresults (Request, QUESTION_ID): Response="You ' re looking at the results of question%s." returnHttpResponse (response%question_id)defvote (Request, question_id):returnHttpResponse ("You ' re voting on question%s."% question_id)

Add these new views into the votes.urls module, just add a few url() function calls:

 fromDjango.urlsImportPath from.ImportViewsurlpatterns=[Path ("", views.index,name='Index'), Path ('<int:question_id>/', Views.detail, Name='Detail'), #votes/1 path ('<int:question_id>/results/', Views.results, Name='Results'), Path ('<int:question_id>/vote/', Views.vote, Name='vote'),]

Then look at your browser, and if you go to "/votes/1/", Django will run the detail() method and show you the problem ID provided in the URL as follows:.

Try "/votes/1/results/" and "/votes/1/vote/"-you'll see the results and voting pages that are temporarily used for placeholders.

When someone requests a page of your site-for example, "/votes/1/"-Django will load the mysite.urls module as it is set in the configuration item ROOT_URLCONF . Django then looks for urlpatterns the name variable and matches the regular expression sequentially. When a match is found ‘votes/‘ , it cuts out the matching text ( "votes/" ), and sends the remaining text----to the "1/" ' Polls.urls ' URLconf for further processing. The remainder of the text here matches ‘<int:question_id>/‘ , making us Django invoke the following form detail() :

Detail (request=

question_id=1<int:question_id>generated by the match. Use angle brackets to "capture" this part of the URL and send it as a keyword argument to the view function. The part of the string above defines the name of the :question_id> variable that will be used to differentiate the matching pattern, and int: then a converter determines what variable type should match the URL path of that part.

Adding unnecessary things to each URL, for example .html , is not necessary. But if you have to add it, it's also possible:

Path ('votes/latest.html', Views.index),

But, don't do this, it's stupid.

3. Next, write a real view

Here's a question: the design of the page is written in the code of the view function. If you want to change the way the page looks, you need to edit the Python code. So let's use Django's templating system, just create a view, and you can separate the design of the page from the code.

First, s create a directory in your vote directory templates . Django will look for template files in this directory.

The configuration item for your project TEMPLATES describes how Django loads and renders the template. The default settings file is set DjangoTemplates to the backend and will be APP_DIRS set to True. This option will cause the DjangoTemplates INSTALLED_APPS "templates" subdirectory to be found in each folder. That's why, even though we didn't modify the DIRS settings as we did in the second part, Django can find the votes template location correctly.

In the directory you just created templates , create a new directory vote s, a file in it index.html . In other words, the path to your template file should be votes/templates/votes/index.html . Because Django will find the corresponding app_directories , you just need to use votes /index.html to refer to this template.

votes/templates/votes/index.html<! DOCTYPE html>"en">"UTF-8"> <title> Home </title>    {%ifLatest_question_list%}    <ul>    {% forQuestioninchLatest_question_list%}        <li><a href="/polls/{{question.id}}/">{{Question.question_text}}</a></li>    {% ENDFOR%}    </ul>    {%Else%}        <p>no polls is available.</p>    {% ENDIF%}</body>

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

 fromDjango.httpImportHttpResponse fromDjango.templateImportLoader from. ModelsImportQuestiondefIndex (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,}returnHttpResponse (Template.render (context, request))

The purpose of the code above is to load the polls/index.html template file and pass it a context. This context is a dictionary that maps variables within a template to Python objects.

Here you can optimize the use of the Render function ()

 fromDjango.shortcutsImportRender from. ModelsImportQuestion#Create your views here.defIndex (Request): Latest_question_list= Question.objects.order_by ('-pub_date') [: 5] Context= {'latest_question_list': Latest_question_list}returnRender (Request,'votes/index.html', context)

A lot of brevity.

Next, write the poll details view

def Detail (request,question_id):     Try :         = Question.objects.get (pk=question_id)    except  question.doesnotexist:          Raise Http404 ("Question does not exist")    return ' votes/detail.html ', {'question': Question})

Html

<! DOCTYPE html>"en">"  UTF-8">    <title> problem details </title>        { for in Question.choice _set.all%}    <li>{{choice.choice_text}}</li>        {% endfor%}    </ul></body>
4. Remove hard-coded URLs from templates

Remember, when we wrote the votes/index.html voting links in, the links were hard-coded:

<li><a href="/votes/{{question.id}}/">{{question.question_text}}</a ></li>

The problem is that hard-coded and strongly-coupled links are difficult to modify for a project that contains many applications. However, because you votes.urls url() define a name for the URL in the function through the name parameter, you can use the {% url %} tag instead of it

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

This tag works by searching for an votes.urls entry with the specified name in the URL definition of the module. You can recall that the URL with the name ' detail ' is defined in the following statement:

... # The ' name ' value as called by the {% URL%} template tagpath ('<int:question_id>/' , Views.detail, name='detail'),...

If you want to change the URL of the poll details view, for example, to change votes/specifics/12/ it, you don't have to modify anything in the template (including other templates), just votes/urls.py modify it slightly:

... # added the word ' specifics 'path ('specifics/<int:question_id>/', Views.detail, name='detail'),...
5. Add a namespace for the URL name

The project has only one application, vote s . In a real Django project, there could be five, 10, 20, and even more applications. How does Django distinguish between URLs with duplicate names? For example, Vote s app has a detail view, and maybe another blog app has a view with the same name. How does Django know {% url %} which URL of the app the tag corresponds to?

The answer is: Add a namespace to the root URLconf. Make a s/urls.py slight change in the vote file, plus app_name set the namespace:

 fromDjango.urlsImportPath from.ImportViewsapp_name='votes'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'),]

Now, edit the votes/index.html file from:

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

Modify to point to a detailed view with a namespace:

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

Python 3+djanjo 2.0.7 Simple Learning (iii)--django view

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.