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
- 二者分别为显示对象列表和显示指定对象的详细信息。
- 每个通用模块需要知道其索要显示的数据(model)
- DetailView期望获取主键pk,因此修改了poll_id为pk
- DetailView默认的模版名为
<app name>/<model name>_detail.html - ListView默认的模版名为
<app name>/<model name>_list.html - DetailView默认的context_object_name为model名子的小写,所以不需要重新指定
- ListView默认的context_object_name为model名子的小写_list,所以需要重新指定
Django初级手册4-表单与通用视图的更多相关文章
- 5 第一个Django第4部分(表单和通用视图)
上一节完成了视图编写,这一节为应用添加投票功能,也就是表单提交. 5.1编写一个简单的表单 5.2使用通用视图 5.3改良视图 5.1编写一个简单的表单 在网页设计中添加Form元素 polls/te ...
- 使用pycharm开发web——django2.1.5(五)表单和通用视图
看了刘江老师教程这么多天,卧槽,我才发现他也曾跻身于行伍之间,interesting 刘老师这波讲解很到位,告诉你如何编写单例视图的时候忽然告诉你,其实不用这么麻烦,我们有通用视图,那些总是要做相似的 ...
- Django 1.10中文文档-第一个应用Part4-表单和通用视图
本教程接Part3开始.继续网页投票应用程序,并将重点介绍简单的表单处理和精简代码. 一个简单表单 更新一下在上一个教程中编写的投票详细页面的模板polls/detail.html,让它包含一个HTM ...
- Django组件之Form表单
一.Django中的Form表单介绍 我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来. 与此同时我们在好多场景下都需要对用户的输入 ...
- Python的Django框架中forms表单类的使用方法详解
用户表单是Web端的一项基本功能,大而全的Django框架中自然带有现成的基础form对象,本文就Python的Django框架中forms表单类的使用方法详解. Form表单的功能 自动生成HTML ...
- 第三百一十一节,Django框架,Form表单验证
第三百一十一节,Django框架,Form表单验证 表单提交 html <!DOCTYPE html> <html lang="en"> <head& ...
- Django框架 之 Form表单和Ajax上传文件
Django框架 之 Form表单和Ajax上传文件 浏览目录 Form表单上传文件 Ajax上传文件 伪造Ajax上传文件 Form表单上传文件 html 1 2 3 4 5 6 7 <h3& ...
- Django 构建模板form表单的两种方法
通常情况下,我们想构建一张表单时会在模板文件login.html中写入 <form action="/your-name/" method="post"& ...
- 第一个Django应用 - 第四部分:表单和类视图
一.表单form 为了接收用户的投票选择,我们需要在前端页面显示一个投票界面.让我们重写先前的polls/detail.html文件,代码如下: <h1>{{ question.quest ...
随机推荐
- Ico初步理解
Ico定义:是一个重要的面向对象编程的法则来削减计算机程序的耦合问题(解耦).通俗理解:把运行中程式的控制权从程式本身那里拿过来,放到配置文件中,通过"反射"找到匹配配置文件总的对 ...
- Apache 的mod_auth_cas模块的介绍和使用
apache的mod_auth_cas模块是一个集成到apache中的cas客户端,一般是配合Apache的反向代理来使用,对某个url的请求先经过apache,apache会判断是否经过cas认证, ...
- linux系统中关于shell变量$*与$@的区别
在我们初学linux系统shell时,可能会感觉$@与$*没什么区别,如下面shell脚本: #!/bin/bash# name:a.sh # echo 'this script $* is: '$* ...
- 如何搭建Packetbeat性能监控
安装与配置JDK 1. 将jdk-8u111-linux-x64.tar.gz上传至Linux的/opt目录下,并执行解压命令: tar -zxvf jdk-8u111-linux-x64.tar. ...
- 【CF845F】Guards In The Storehouse 插头DP
[CF845F]Guards In The Storehouse 题意:一个n*m的房间,每个格子要么是障碍要么是空地.对于每个空地你可以选择放或者不放守卫.一个守卫能保护到的位置是:他右面的一行空地 ...
- centos7下安装nmon后,无法运行,提示 cannot execute binary file或/lib64/ld64.so.1不存在
在centos 7.1上安装nmon后,从管网(http://nmon.sourceforge.net/pmwiki.php?n=Site.Download)下载tar包解压后,两台机器一台提示 ca ...
- mysql操作常用技巧
删除一张表的数据,条件在另一张表 delete a from A a,B b where a.tel=b.tel and a.code=b.code and a.day='201808';
- php代码不支持多维数组,注释和没有缓存功能。
php代码:simplet.class.php<?phpclass SimpleT {private $t_vars;private $templates_dir;private $templa ...
- 深圳MPD大会,五大专题一会尽享
深圳MPD大会,五大专题一会尽享 2013年9月,深圳的高温将慢慢褪去,炎炎夏日也会变得稍微清凉一些.但9月It届的峰会活动却没有丝毫的锐减.9月7-8日深圳将迎来MPD大会2013的收官之站. MP ...
- Java编程思想第四版随书源码官方下载方法
见不少人在找net.mindview.util.Print,CSDN上有下载,收积分,以下是官网的下载方法,免费: 官网链接:http://mindview.net/ 电子书下载地址:http://w ...