Django项目开发举例之用户界面表单(6)
1.编写一个简单的表单
首先让我们来丰富一下模板(“myapp/detail.html”),让它包含一个HTML<form> 元素:
#---------------------------------------------------------------------------------------------------------------------------------------------
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'myapp: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>
#---------------------------------------------------------------------------------------------------------------------------------------------
简要说明:
- 在detail网页模板中,我们为Question对应的每个Choice都添加了一个单选按钮用于选择。每个单选按钮的value属性是对应的各个Choice的ID。每个单选按钮的name是"choice"。这意味着,当有人选择一个单选按钮并提交表单提交时,它将发送一个POST数据choice=#,其中# 为选择的Choice的ID。这是HTML 表单的基本概念。
- 我们设置表单的action为{% url 'myapp:vote' question.id %},并设置 method="post"。使用method="post"(与其相对的是method="get")是非常重要的,因为这个提交表单的行为会改变服务器端的数据。 无论何时,当你需要创建一个改变服务器端数据的表单时,请使用 method="post"。这不是Django的特定技巧;这是优秀的网站开发实践。
- forloop.counter指示for标签已经循环多少次。
- 由于我们创建一个POST表单(它具有修改数据的作用),所以我们需要小心跨站点请求伪造。 谢天谢地,你不必太过担心,因为Django已经拥有一个用来防御它的非常容易使用的系统。 简而言之,所有针对内部URL的POST表单都应该使用{% csrf_token %}模板标签。
from django.shortcuts import render
from django.http import HttpResponse,Http404,HttpResponseRedirect
from django.template import RequestContext, loader
from .models import Question,Choice
from django.shortcuts import render,get_object_or_404
from django.core.urlresolvers import reverse
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, 'myapp/detail.html', {
'question': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('myapp:results', args=(p.id,)))
#---------------------------------------------------------------------------------------------------------------------------------------------
有些新的东西我们来解释一下:
-
request.POST 是一个类似字典的对象,让你可以通过关键字的名字获取提交的数据。 这个例子中,request.POST['choice'] 以字符串形式返回选择的Choice的ID。request.POST 的值永远是字符串。
注意,Django还以同样的方式提供request.GET用于访问GET数据 —— 但我们在代码中显式地使用request.POST,以保证数据只能通过POST调用改动。
-
如果在POST数据中没有提供choice,request.POST['choice']将引发一个KeyError。上面的代码检查KeyError,如果没有给出choice将重新显示Question表单和一个错误信息。
-
在增加Choice的得票数之后,代码返回一个 HttpResponseRedirect而不是常用的HttpResponse。HttpResponseRedirect只接收一个参数:用户将要被重定向的URL(请继续看下去,我们将会解释如何构造这个例子中的URL)。
正如上面的Python注释指出的,你应该在成功处理POST数据后总是返回一个HttpResponseRedirect。 这不是Django的特定技巧; 这是那些优秀网站在开发实践中形成的共识。
-
在这个例子中,我们在HttpResponseRedirect的构造函数中使用reverse()函数。这个函数避免了我们在视图函数中硬编码URL。它需要我们给出我们想要跳转的视图的名字和该视图所对应的URL模式中需要给该视图提供的参数。 在本例中,使用在教程3中设定的URLconf, reverse() 调用将返回一个这样的字符串:
'/myapp/3/results/'
... 其中3是p.id的值。重定向的URL将调用'results'视图来显示最终的页面。
正如在教程3中提到的,request是一个 HttpRequest对象。
当有人对Question进行投票后,vote()视图将请求重定向到Question的结果界面。让我们来编写这个视图:
#---------------------------------------------------------------------------------------------------------------------------------------------
def results(request,question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'myapp/results.html', {'question': question})
#---------------------------------------------------------------------------------------------------------------------------------------------
加下来创建results视图的模版文件myapp/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 'myapp:detail' question.id %}">Vote again?</a>
#---------------------------------------------------------------------------------------------------------------------------------------------
2.使用通用视图来简化代码
目前我们编写代码的思路是Web开发中的一个常见情况:根据URL中的参数从数据库中获取数据、载入模板文件然后返回渲染后的模板。 由于这种情况非常普遍,Django提供了一种叫做“generic views”的系统可以方便地进行处理。
Generic views会将常见的模式抽象化,可以使你在编写app时甚至不需要编写Python代码。
让我们将我们的投票应用转换成使用通用视图系统,这样我们可以删除许多我们的代码。我们仅仅需要做以下几步来完成转换: 我们将:
- 1)转换URLconf。
- 2)删除一些旧的、不再需要的代码。
- 3)引进基于Django通用视图的新视图。
- 改写myapp/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'),
]
- #---------------------------------------------------------------------------------------------------------------------------------------------
- 改写myapp/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 Question,Choice
# Create your views here.
class IndexView(generic.ListView):
template_name = 'myapp/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 = 'myapp/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'myapp/results.html'
def vote(request,question_id):
question=get_object_or_404(Question,pk=question_id)
return render(request,'myapp/vote.html',{'question':question})
- #---------------------------------------------------------------------------------------------------------------------------------------------
- 在myapp/templates/myapp/下创建question_detail.html文件复制detail.html文件即可,创建vote.html内容写{{question}}
-
我们在这里使用两个通用视图:ListView 和 DetailView。这两个视图分别抽象“显示一个对象列表”和“显示一个特定类型对象的详细信息页面”这两种概念。
- 每个通用视图需要知道它将作用于哪个模型。 这由model 属性提供。
- DetailView期望从URL中捕获名为"pk"的主键值,因此我们把polls/urls.py中question_id改成了pk以使通用视图可以找到主键值 。
默认情况下,通用视图DetailView 使用一个叫做<app name>/<model name>_detail.html的模板。在我们的例子中,它将使用 "polls/question_detail.html"模板。template_name属性是用来告诉Django使用一个指定的模板名字,而不是自动生成的默认名字。 我们也为results列表视图指定了template_name —— 这确保results视图和detail视图在渲染时具有不同的外观,即使它们在后台都是同一个 DetailView。
类似地,ListView使用一个叫做<app name>/<model name>_list.html的默认模板;我们使用template_name 来告诉ListView 使用我们自己已经存在的"polls/index.html"模板。
在之前的教程中,提供模板文件时都带有一个包含question 和 latest_question_list 变量的context。对于DetailView ,question变量会自动提供—— 因为我们使用Django 的模型 (Question), Django 能够为context 变量决定一个合适的名字。然而对于ListView, 自动生成的context 变量是question_list。为了覆盖这个行为,我们提供 context_object_name 属性,表示我们想使用latest_question_list。作为一种替换方案,你可以改变你的模板来匹配新的context变量 —— 但直接告诉Django使用你想要的变量会省事很多。
启动服务器127.0.0.1:8000/myapp/1/,使用一下基于通用视图的新投票应用。