表单的编写

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,所以需要重新指定

Django初级手册4-表单与通用视图的更多相关文章

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

    上一节完成了视图编写,这一节为应用添加投票功能,也就是表单提交. 5.1编写一个简单的表单 5.2使用通用视图 5.3改良视图 5.1编写一个简单的表单 在网页设计中添加Form元素 polls/te ...

  2. 使用pycharm开发web——django2.1.5(五)表单和通用视图

    看了刘江老师教程这么多天,卧槽,我才发现他也曾跻身于行伍之间,interesting 刘老师这波讲解很到位,告诉你如何编写单例视图的时候忽然告诉你,其实不用这么麻烦,我们有通用视图,那些总是要做相似的 ...

  3. Django 1.10中文文档-第一个应用Part4-表单和通用视图

    本教程接Part3开始.继续网页投票应用程序,并将重点介绍简单的表单处理和精简代码. 一个简单表单 更新一下在上一个教程中编写的投票详细页面的模板polls/detail.html,让它包含一个HTM ...

  4. Django组件之Form表单

    一.Django中的Form表单介绍 我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来. 与此同时我们在好多场景下都需要对用户的输入 ...

  5. Python的Django框架中forms表单类的使用方法详解

    用户表单是Web端的一项基本功能,大而全的Django框架中自然带有现成的基础form对象,本文就Python的Django框架中forms表单类的使用方法详解. Form表单的功能 自动生成HTML ...

  6. 第三百一十一节,Django框架,Form表单验证

    第三百一十一节,Django框架,Form表单验证 表单提交 html <!DOCTYPE html> <html lang="en"> <head& ...

  7. Django框架 之 Form表单和Ajax上传文件

    Django框架 之 Form表单和Ajax上传文件 浏览目录 Form表单上传文件 Ajax上传文件 伪造Ajax上传文件 Form表单上传文件 html 1 2 3 4 5 6 7 <h3& ...

  8. Django 构建模板form表单的两种方法

    通常情况下,我们想构建一张表单时会在模板文件login.html中写入 <form action="/your-name/" method="post"& ...

  9. 第一个Django应用 - 第四部分:表单和类视图

    一.表单form 为了接收用户的投票选择,我们需要在前端页面显示一个投票界面.让我们重写先前的polls/detail.html文件,代码如下: <h1>{{ question.quest ...

随机推荐

  1. [原]secureCRT 改变显示宽度

    1.首先全局设置:Options - Global Options - Terminal - Appearance - Maximumcolumns 最大只能设置成1024(推荐256),设置越大越占 ...

  2. 更新jenkins插件,报错 Perhaps you need to run your container with "-Djava.awt.headless=true"?

    Configuring the Java environment variables vi ~/.bash_profile 在最后一行加入: export JAVA_OPTS=-Djava.awt.h ...

  3. 【BZOJ4445】[Scoi2015]小凸想跑步 半平面交

    [BZOJ4445][Scoi2015]小凸想跑步 Description 小凸晚上喜欢到操场跑步,今天他跑完两圈之后,他玩起了这样一个游戏. 操场是个凸n边形,N个顶点按照逆时针从0-n-l编号.现 ...

  4. 安装coreseek与sphinx遇见的问题

    1.问题 using config file 'etc/csft.conf'...indexing index 'xml'...WARNING: source 'xml': xmlpipe2 supp ...

  5. POJ-1644 To Bet or Not To Bet(概率DP)

    To Bet or Not To Bet Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 1668 Accepted: 541 D ...

  6. 基于元胞自动机NaSch模型的多车道手动-自动混合驾驶仿真模型的Matlab实现

    模型的建立基本来自于:http://www.doc88.com/p-2078634086043.html 花了一天半的时间用新学会的matlab实现了一下. ───────────────────── ...

  7. SHU 414 - 字符串进制转换

    题目链接:http://acmoj.shu.edu.cn/problem/414/ 很咸鱼的网上拉了个进制转换模板过来,因为数组开的太小一直WA,后来一气之下MAXN开到1e5,真是蓝瘦…… 后来实在 ...

  8. contenttypes - django组件

    一.contenttypes介绍 它的作用:可以通过两个字段让表和N张表创建FK关系 二.ContentType.GenericForeignKey.GenericRelation 表结构: from ...

  9. Linux目录【持续更新中】

    故障排除 服务器为什么这么慢?耗尽了CPU.RAM和磁盘I/O资源 服务 ELK服务基础 基础 常用命令 curl命令 Nginx服务基础 Nginx正向代理配置 Nginx文件下载服务器 Nginx ...

  10. 如何用 Keynote 制作动画演示(转)

    原文:如何用 Keynote 制作动画演示 Keynote 里的很多特效可以用来制作效果不错的演示,一页页的将需要演示的内容交代清楚后,直接输出成 m4v 的视频格式,为了方便贴到博客或者发布到 Tw ...