Public opinion survey Django implementation (four)

Label DjangoTemplates
306 people read comments(0) Collection Report

We went on to have a section at the end of the beginning to learn, in a section, we mainly to understand the Django template use, namely templates. In this section, we focus on simple form processing and tailoring our code.

Write a simple form

Let's update our detail template ("polls/detail.html"), adding HTML<form>Elements.

<H1>Turning question.question_text}}< /H1>

{%IfError_message%}<P><Strong>Turning error_message}}< /Strong>< /P>{%Endif%}

<Form Action="{%URL'polls:vote'}" Method="Post">
    <Input Type="Radio" Name="Choice" ID="ChoiceTurning forloop.counter}}" Value="Turning}}">
    <Label For="ChoiceTurning forloop.counter}}">Turning choice.choice_text}}< /Label>< /Br>

<Input Type="Submit" Value="Vote">

< /Form>

Simply describe:
- show a group of radio buttons above the template for each question. The value of each button (value) is an option for the related problem ID. The name of each button is "choice" ". That means that, when a user selects one of the options box and submit the form, will send post dataChoice=#Among them, # is the corresponding options ID. This is the basic concept of the HTML form.
- we set the action for the formURL'polls:vote'{%}And we setPost "method=". Using the post method (and using the get method corresponding) is very important, because the submit form of behavior will change the server data. Whenever you create a form that can modify the server data, be sure to use it.Post "methon=". This technique is not proprietary to Django. This is just a good web development skills.
- forloop.counter marks the number of times that for tags appear in this cycle.
- now that we have created a post form (the form may affect modify data), we need to worry about the request through the site of camouflage. Fortunately, we do not have to worry too much, because Django provides a simple and easy to use the system to stop him. In simple terms, the goal is to use all of the POST forms within the URLs.{% crsf_token%}Template tags.

Now, we create a view to process the data submitted. In the last section, we created a URLconf that contains the following line.


(URLR'^ (P<question_id>\d+) /vote/$',, name='vote'),

We also create a temporary implementation of vote () function. Now we come to really use it. Add the following code to the polls/

# -*- coding:utf-8 -*-
FromDjango.httpImportHttpResponse, HttpResponseRedirect
FromDjango.shortcutsImportGet_object_or_404, render



Def Vote(request, question_id):
P = get_object_or_404 (Question, pk=question_id)

Selected_choice = p.choice_set.get (pk=request.POST['choice'])
    Except(KeyError, Choice.DoesNotExit):
        ReturnRender (request,'polls/detail.html'{.
            'question': p,
            'errot_message':"Did not select a choice. You"
= selected_choice.votesOne ()
        Must return to HttpResponseRedirect # after each successful processing of POST data.
        This can avoid the two time to #
        ReturnHttpResponseRedirect (reverse ('polls/results', args= (

The code contains the following things:

  • Request.POST is similar to a dictionary object, we can make the key name to access the data submitted. In this example,Request.POST['choice']Returns the ID of the selected option, here is the string.Request.POSTValue is always a string.
    Note that Django also providesRequest.GETGET data to access the way, but forRequest.POSTOnly in the code to get access to the corresponding data, this you can go to understand the difference between the get request and post requests.

  • If the choice option is not available in the POST data, thenRequest.POST['choice']KeyError exception will be thrown. The above code check keyerror exception, if there is no choice and re display with the form question on the error information.

  • After increasing the number of options, the code returns an HttpResponseRedirect rather than a normal HttpResponse. HttpResponseRedirect uses a single parameter: that is, the user will be redirected to the URL address.
  • In the HttpResponseRedirect structure of this example we use the reverse () function. This function helps us to avoid the occurrence of a view function in the hard encoding URL address. He is given the name of the view that we want to pass to the URL and the variable portion of the point in the view. In this example, the use of in the previous section we set the urlconf, and ultimately reverse) (call will return similar to the following string:'/polls/3/results', 3 of which areP.idValue. This redirection URL then calls the 'results' view to display the final page.

Vote () views will be redirected to the results page of the problem after the user is voted on the issue. Now let's rewrite this page:

Def Results(request, question_id):
Question = get_object_or_404 (Question, pk=question_id)
    ReturnRender (request,'polls/results.html'{.'question'Question})

Here we add the results template:

Create a polls/results.html template:


<H1>Turning question.question_text}}< /H1>

    <Li>Turning choice.choice_text}}-Turning choice.votes}}VoteTurning choice.votes|Pluralize}}< /Li>
< /UL>

<A Href="{%URL'polls:detail'}">Again Vote?< /A>

Now, we're going to /polls/1/ in the browser to vote for the relevant issues. After each vote, you can see the results. If you click Submit, you will see the error message if you have no option.

Now look at my running results:

Write the picture here.

Write the picture here.

Using a common view: reducing the code is better

Detail () and results () view is very simple - as mentioned above, too redundant. The index () view of the voting list is the same.

These views represent the common examples of basic web development: the URL parameter retrieves the data from the database and load the template and returns a template is rendered. Because these are the same, so it provides a shortcut to Django, become "common view" system.

General tries to system abstraction in addition to general regular, which makes us may not need to write Python code to an application component.

Let's use a common view of our application, so we can delete a larger code. We just need a few steps to make the switch.

  1. Conversion URLconf
  2. Delete some of the old, do not need view
  3. General view based on Django to introduce a new view

Modify URLconf

First, open the polls/ and modify it like the following:

FromDjango.conf.urlsImportPatterns, URL


Urlpatterns = patterns (=.',
    # ex: /polls/
(URLR'^$', views.IndexView.as_view (), name='index'),
    # ex: /polls/5/
(URL(r'^? P<pk>\d+) /$', views.DetailView.as_view (), name='detail'),
    # ex: /polls/5/results
(URLR'^ (P<pk>\d+) /results/$', views.ResultsView.as_view (), name='results'),
    # ex: /polls/5/vote/
(URLR'^ (P<question_id>\d+) /vote/$',, name='vote'),

Note that the regular match between the<question_id>Changed into<pk>.

Modify view

Next, we will remove our old index, detail and results view, and then use the Django common view. Open the polls/ file and modify it as follows:

# -*- coding:utf-8 -*-
FromDjango.httpImportHttpResponse, HttpResponseRedirect
FromDjango.shortcutsImportGet_object_or_404, render


Class IndexView(generic.ListView):
Template_name ='polls/index.html'
Context_object_name ='latest_question_list'

    Def Get_queryset(self):
        "" "" "the last five published questions. Return"""

template_name =“民意调查/ HTML的细节。

template_name =“民意调查/结果HTML”。

DEF 投票(要求,question_id)


  • 每一个通用视图都需要知道他们操作的模型是什么。这个通过模型属性提供
  • DetailView通用视图需要从URL中获取称为“PK”的主键,这就是为什么刚刚在PY中修改URL。question_idPK的原因了。

默认情况下,通用视图使用称为DetailView<应用程序名称> / <名称> _detail.html模型作为模板。在我们的例子中,他会使用模板”民意调查/ question_detail .html”。属性template_name被用来告诉Django使用能够哪一个模板代替默认模板我们也为指定了template_name结果。

相似的,ListView通用视图使用默认的模板,称为<应用程序名称> / <名称> _list.html模型,我们同样为他指定了我们自己的模板。




    • 访问:54265次
    • 积分:二千五百四十八
    • 等级:
    • 排名:8313名第
    • 原创:179篇
    • 转载:3篇
    • 译文:8篇
    • 评论:36条
    Latest comments