MasterofProject

Public opinion survey Django implementation (four)

Label DjangoTemplates
306 people read comments(0) Collection Report
Classification:

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'question.id%}" Method="Post">
{%Csrf_token%}
{%ForChoiceInQuestion.choice_set.all%}
    <Input Type="Radio" Name="Choice" ID="ChoiceTurning forloop.counter}}" Value="Turning choice.id}}">
    <Label For="ChoiceTurning forloop.counter}}">Turning choice.choice_text}}< /Label>< /Br>
{%Endfor%}

<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'{% question.id%}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.

Polls/urls.py

(URLR'^ (P<question_id>\d+) /vote/$', views.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/views.py:

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

FromPolls.modelsImportQuestion

....

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

    Try:
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"
})
    Else:
= selected_choice.votesOne
Selected_choice.save ()
        Must return to HttpResponseRedirect # after each successful processing of POST data.
        This can avoid the two time to #
        ReturnHttpResponseRedirect (reverse ('polls/results', args= (p.id))

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:

Polls/templates/polls/results.html

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

<UL>
    {%ForChoiceInQuestion.choice_set.all%}
    <Li>Turning choice.choice_text}}-Turning choice.votes}}VoteTurning choice.votes|Pluralize}}< /Li>
    {%Endfor%}
< /UL>

<A Href="{%URL'polls:detail'question.id%}">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/urls.py and modify it like the following:

FromDjango.conf.urlsImportPatterns, URL

FromPollsImportViews

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/$', views.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/view.py file and modify it as follows:

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

FromPolls.modelsImportQuestion


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"""
        Return的问题。order_by(对象。“pub_date”)[:]

 DetailView(通用。DetailView)
模型=问题
template_name =“民意调查/ HTML的细节。

 resultsview(通用。DetailView)
模型=问题
template_name =“民意调查/结果HTML”。

DEF 投票(要求,question_id)
    #和原来一样

我们使用了两个通用视图:ListView和DetailView。这两个视图抽象除了”显示对象列表”和”现象特定对象详细信息”的概念。

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

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

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

在之前的小节中,模板已经被提供了语境,也就是上下文,该上下文包含问题和latest_question_list变量。对于DetailView,问题已经被自动提供了。我们使用Django的模型(的问题),所以Django能够决定为上下文变量使用一个近似的名称。然而,对于ListView,自动生成的上下文变量是question_list为了重写,我们可以使用。context_object_name属性,指定我们想要使用的latest_question_list。这样的话,通过Django通用视图提供的属性,我们就可以指定我们想使用的变量了。

下面我们来运行一下,看一下效果:

运行效果和上面的。

猜你在找
查看评论
*以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:54265次
    • 积分:二千五百四十八
    • 等级:
    • 排名:8313名第
    • 原创:179篇
    • 转载:3篇
    • 译文:8篇
    • 评论:36条
    博客专栏
    文章存档
    Latest comments