啊峰哥

5 第一个Django第4部分(表单和通用视图)

上一节完成了视图编写,这一节为应用添加投票功能,也就是表单提交。

5.1编写一个简单的表单

5.2使用通用视图

5.3改良视图

 

5.1编写一个简单的表单

在网页设计中添加Form元素

polls/templates/polls/detail.html

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

解释:

--input那一行,type=’radio’,指的是,该输入是可选择的一个类型,我们选什么,值就等于相应的value。其中value=choice.id。所以我们获得的是对象的id。

--使用method="post",表示这个提交表单的行为会改变服务端数据

--forloop.counter,相当于一个for循环,来进行计数

--因为创建了一个POST表单,需要请求伪造(我也不知道为什么),所以,POST表单应该使用{% csrf_token %}模板标签。

 

为提交数据添加一个url链接

polls/urls.py

url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),

添加连接后,在视图中创建vote()函数提交投票数据

polls/views.py

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse

from .models import Choice, Question
# ...
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.DoesNotExist):
        # 错误页面
        return render(request, 'polls/detail.html', {
            'question': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        #返回结果页面
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

解释:

--requestion.POST是一个类似于字典的对象,request.POST[‘choice’]获取的是对象中的choice值的id,如果没有提供choice值,就会引发一个keyError错误。

--投票成功后,代码返回的是HttpResponseRedirect而不是常用的HttpRespnse,HttpResponseRedirect只接收一个参数:用户将要被重定向的URL。在成功处理POST数据后总是返回一个

    HttpResponseRedirect。 这不是Django的特定技巧; 而是那些优秀网站在开发实践中形成的共识。

--HttpResponseRedirect的构造函数中使用reverse()函数。这个函数避免了我们在视图函数中硬编码URL,参数为(视图名字,对应视图的URL需要的参数)。

 

用户投票完成后,显示什么呢?结果吧,所以编写一个结果视图和结果页

    视图

polls/views.py

from django.shortcuts import get_object_or_404, render


def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})

    页面

polls/templates/polls/results.html

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

现在,在你的浏览器中访问/polls/1/然后为Question投票。你应该看到一个投票结果页面,并且在你每次投票之后都会更新。 如果你提交时没有选择任何Choice,你应该看到错误信息。

5.2使用通用视图

根据URL中的参数---从数据库中获取数据----载入模版然后---返回渲染模版

由于这种情况很普遍,Django提供了一种叫做“generic views”的系统可以方便地进行处理。这就是我们要引用的通用视图,使视图变得更简便。

 

但是一般来说,编写Django应用时候,应该先估计一下能不能用通用视图来解决,如果可以,一开始就使用

 

改良视图

删除旧的indexdetailresults 视图,并用Django的通用视图代替。打开polls/views.py文件,并将它修改成:

polls/views.py

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic

from .models import Choice, Question


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'


def vote(request, question_id):
    ... # 这里不改

解释:

--这里用了两种通用视图,分别表示

    ListView,显示一个对象列表

    DetailView,显示一个特定对象的详细页面

--template_nam属性属性,指定一个模版名字

   model属性指定模型

--对于ListView,自动生成的context变量是question_list(不管他)。

   这里使用context_object_name属性(如果=A),改变了context变量的名字,这样模版就会匹配相应A。{{ A }}

--Detail 会默认从URL中获取名为'pk’的主键值,所以需要把polls.py中的’question_id’改为’pk’,如下

 

改良URLconf

polls/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

解释:第二个和第三个模式的正则表达式中,匹配的模式的名字由<question_id> 变成 <pk>

 

到这里,这一节的内容结束了,启动服务器,使用一下新投票应用吧

posted on 2017-10-26 14:06  啊峰哥  阅读(410)  评论(0编辑  收藏  举报

导航