Django初级手册4-表单与通用视图

表单的编写

1. detail.html模版的编写

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

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

<form action="{% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% for choice in poll.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>

错误信息是为了没有选择直接提交做准备的。
纯HTML表单的提交如下:

<form action="/example/html/form_action.asp" method="get">
  <input type="radio" name="sex" value="male" /> Male<br />
  <input type="radio" name="sex" value="female" /> Female<br />
  <input type="submit" value="Submit" />
</form>
  • 上述代码中,action调用vote url从而调用vote的视图函数。
  • input的名字相同,可以提供单项选择。
  • label的for标签可和input的id标签对应,label标签就是为了对input元素进行标注。
  • forloop.counter相当于C语言中for的计数器i。
  • 所有的POST表单的提交都应该注意安全,{% csrf_token %}可保证该POST只接受内置的URL

2. view.py的修改

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from polls.models import Choice, Poll
# ...
def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the poll voting form.
        return render(request, 'polls/detail.html', {
            'poll': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
  • request.POST是一个类似词典结构的结构,可以接受来自POST强求表单的信息,它的值总受字符串,request.GET也是相同的方式。
  • 如果POST中没有choice的信息,则会重定向到vote页面,并有警告提示。
  • 在成功处理POST数据后,都应该重定向,这在所有的网络开发中都是适用的。原因在注释中。
  • reverse函数可以避免生硬难看的URL,和URL中的形式保持一致。

3. results的编写

view.py中

from django.shortcuts import get_object_or_404, render

def results(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    return render(request, 'polls/results.html', {'poll': poll})  

results.html

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

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

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

使用通用视图

是否选用通用视图的方法是应该一开始就决定的,教程采用这种顺序是因为更好的说明概念。
可以发现detail()和results()函数是十分相似的。

1. 修正URLS

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)

2. 修正views

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 polls.models import Choice, Poll

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

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


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


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

def vote(request, poll_id):
    ....

ListView与DetailView

  1. 二者分别为显示对象列表和显示指定对象的详细信息。
  2. 每个通用模块需要知道其索要显示的数据(model)
  3. DetailView期望获取主键pk,因此修改了poll_id为pk
  4. DetailView默认的模版名为<app name>/<model name>_detail.html
  5. ListView默认的模版名为<app name>/<model name>_list.html
  6. DetailView默认的context_object_name为model名子的小写,所以不需要重新指定
  7. ListView默认的context_object_name为model名子的小写_list,所以需要重新指定
posted @ 2014-02-27 09:50  Solon Tan  阅读(304)  评论(0编辑  收藏  举报