5 Post实现django表单
本节大纲
1.article-detail 评论页面的准备工作
(1)model层创建评论模型
class Comment(models.Model):
"""创建评论模型"""
name = models.CharField(null=True, blank=True, max_length=50)
comment = models.TextField(null=True, blank=True) def __str__(self):
return self.comment
(2)数据合并
(3)注册到admin.py文件中
(4)admin后台查看
(5)View层:创建评论视图模型
from firstapp.models import People,Aritcle,Comment def detail(request):
"""评论视图模型"""
context = {}
comment_list = Comment.objects.all()
context['Comment_list'] = comment_list
detail_page = render(request,'article-detail.html',context)
return detail_page
(6)urls 添加
from django.conf.urls import include, url
from django.contrib import admin
from firstapp.views import first_try,index,detail urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^first_try/', first_try),
url(r'^index', index,name='index'),
url(r'^detail', detail,name='detail'),
]
(7)article-detail.html 页面:替换静态文件
{% load staticfiles %} <link rel="stylesheet" href="{% static 'css/semantic.css'%}" media="screen" title="no title" charset="utf-8"> background:url({% static 'images/star_banner.jpg'%});
<!DOCTYPE html>
{% load staticfiles%}
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="{% static 'css/semantic.css'%}" media="screen" title="no title" charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Oswald|Raleway" rel="stylesheet"> <style type="text/css">
.ui.segment.container {
width:700px;
} p {
font-family: 'Raleway', sans-serif;
font-size:18px;
} body {
background:url({% static 'images/star_banner.jpg'%});
background-size:cover;
background-repeat:no-repeat;
background-attachment:fixed
} </style>
</head>
<body>
<div class="ui image">
<img src="" alt="" />
</div>
<div class="ui segment padded container" >
<h1 class="ui header" style="font-family:'Oswald', sans-serif;font-size:40px">
Indonesia pointed at Christmas
</h1>
<p>
his is how it happens:
The most sensible alternative to a life of unbearable hardship is to take a chance on a rubber dinghy in Indonesia pointed at Christmas Island, which is part of Australia. If a refugee survives, this person is not praised for valor but rather ejected 4,000 miles away to another island. Nauru Regional Processing Center. Processing sounds temporary, and it is, in the same way purgatory is temporary. Asylum seekers have been known to wait five years for intercession in the form of a “refugee status determination,” or RSD.
The agony of waiting is what caused the July 2013 riot. RSDs that were promised were not delivered, and asylum seekers protested. They threw rocks at police and lit fire to buildings. No one was hurt, but the fires caused $60 million in damage. It was probably the most power they’d ever wielded. Nauruan police arrested 153 people around 9:30 p.m. and charged them with rioting. But nothing changed. If anything, the detainees were more forlorn than ever.
Depression was becoming rampant. The older children noticed it, and the little ones, too, though they couldn’t quite understand. Something was wrong. Happiness should be easy at that age. But not in Nauru.
Once, a teacher noticed her student searching the ground for something while waiting for the bus to take him home from school. He was a nice little boy. He’d been given something that morning, a sticker. What a thing. But now he’d lost it, and he anxiously combed the dirt and gravel. “Leave it,” the teacher said. “You can find it later.” The boy said nothing. He just slumped into a pile and sobbed.
When the protests of Sept. 30 amounted to nothing, it was as though a reservoir of grief broke through the last levee, and hopelessness flooded the little camp.
All around were thoughts of suicide. One asylum seeker, Yusuf, told his case manager he thought the mood in the camp was worse than ever. A week earlier, the Australian government had taken the unprecedented step of paying Cambodia (as it paid Nauru) to resettle refugees there. The head of the U.N. refugee agency called it “a worrying departure from international norms” because Australia was essentially paying a poor, unsuitable country to take over its own moral and legal obligations. But Cambodia wanted the money, Australia didn’t want the refugees and to this day the plan is still in place.
</p>
</div> <!-- Comments&Form's here -->
<div class="ui segment container" style="width:700px;">
<h3 class="ui header" style="font-family:'Oswald', sans-serif;">Comments</h3>
<div class="ui comments">
<div class="comment">
<div class="avatar">
<img src="http://semantic-ui.com/images/avatar/small/matt.jpg" alt="" />
</div>
<div class="content">
<a href="#" class="author">John Doe</a>
<div class="metadata">
<div class="date">2 days ago</div>
</div>
<p class="text" style="font-family: 'Raleway', sans-serif;">
Great article !
</p>
</div>
</div> </div>
<div class="ui divider"></div>
<form class="ui form" action="" method="post">
<div class="field">
<label> name</label>
<input type="text" name="name" value="">
</div>
<div class="field">
<label>comment</label>
<textarea></textarea>
</div> <button type="submit" class="ui blue button" >Click</button>
</form> </div> </body>
</html>
2.渲染表单
(1)view.py中的 Django自带的表单类
from django.shortcuts import render,HttpResponse
from firstapp.models import People,Aritcle,Comment
from django.template import Context,Template
from django import forms
# Create your views here. class CommentForm(forms.Form):
"""定义一个Django自带的表单类"""
name = forms.CharField(max_length=50)
comment = forms.CharField()
(2) 实例化一个表单,装入context,传入模板层
def detail(request):
"""创建评论视图"""
form = CommentForm() #实例化一个表单 context ={}
comment_list = Comment.objects.all() #获取comment评论的所有数据
context['comment_list'] = comment_list
context['form'] = form
comment_page = render(request,'article-detail.html',context) #render函数
return comment_page
(3) 渲染html
- 删除手写的表单
- 添加View层传递的表单
- 表单模板变量
(4)修改form表单的class
- 两个label各自包含在一个 p标签
{{ form.as_p }}
(5)html代码:form表单
<!-- Comments&Form's here -->
<div class="ui segment container" style="width:700px;">
<h3 class="ui header" style="font-family:'Oswald', sans-serif;">Comments</h3>
<div class="ui comments"> {% for comment in comment_list %}
<div class="comment">
<div class="avatar">
<img src="http://semantic-ui.com/images/avatar/small/matt.jpg" alt="" />
</div>
<div class="content">
<a href="#" class="author">{{ comment.name }}</a>
<div class="metadata">
<div class="date">2 days ago</div>
</div>
<p class="text" style="font-family: 'Raleway', sans-serif;">
{{ comment.comment }}
</p>
</div>
</div>
{% endfor %} </div>
<div class="ui divider"></div>
<form class="ui form" action="" method="post"> {{ form.as_p }}
{% csrf_token %}
<button type="submit" class="ui blue button" >Click</button>
</form> </div>
3.绑定表单&返回校验结果
(1)表单文件移动到form.py
(2)绑定表单,提交表单
- Get方法:传递表单,我要填写表单
- Post方法:我要提交数据,你要校验数据
(3)CSRF跨站攻击的防护:证明我还是我,令牌和数据一起提交
(4)post方法提交的数据
(5)表单校验功能
(6)打印errors,返回一个列表,所有的错误信息都存储在这里
4.表单存储数据
(1)判断校验是否通过
- 通过返回数据,不通过什么都不返回
(2)通过后,查看清洗过的数据
(2)获取字典中的name comment ,把数据储存到Comment模型的实例c中
(3)重定向到detail本页
(4)提交评论显示成功
(5)评论视图模型代码
from django.shortcuts import render,HttpResponse,redirect
from firstapp.models import People,Aritcle,Comment
from django.template import Context,Template
from firstapp.form import CommentForm def detail(request):
"""创建评论视图"""
if request.method == 'GET':
form = CommentForm() #实例化一个表单
if request.method == 'POST':
form = CommentForm(request.POST) #提交数据
print(form) if form.is_valid(): #判断表单的数据是否通过验证;
print(form.is_valid) #返回布尔值,True 或者False
print(form.cleaned_data)
name = form.cleaned_data['name']
comment = form.cleaned_data['comment']
c = Comment(name=name,comment=comment) #把数据储存到Comment模型的实例c中
c.save() #保存到数据库
return redirect(to='detail') context ={}
comment_list = Comment.objects.all() #获取comment评论的所有数据
context['comment_list'] = comment_list context['form'] = form comment_page = render(request,'article-detail.html',context) #render函数
return comment_page
5.定制表单的验证逻辑
(1)comment评论的类型
widget=forms.Textarea(), #comment 表单的类型为Textarea
- 不推荐
(2)error_messages报错信息
error_messages = { 'required':'请输入内容'}
(3)验证器参数
from django.core.exceptions import ValidationError
def words_validator(comment):
if len(comment) < 4:
raise ValidationError('内容不足4个字符') #当comment不足4个字符,升起一个错误
validators = [words_validator], #验证器
(4)验证器2
(5)form.py 代码
from django import forms
from django.core.exceptions import ValidationError
# Create your views here. def words_validator(comment):
"""验证器函数"""
if len(comment) < 4:
raise ValidationError('内容长度不足4个字符') def comment_validator(comment):
"""过滤器"""
if 'a' in comment:
raise ValidationError('不能包含a这个字符') class CommentForm(forms.Form):
"""评论表单类"""
name = forms.CharField(max_length=50)
comment = forms.CharField(
widget=forms.Textarea(), error_messages = { #错误信息修改
'required':'请输入内容'
}, validators = [words_validator,comment_validator] #验证器参数 ) #x修改表单样式
6.定制表单的手工渲染
(1)定制sematic ui 的表单
<form class="ui form"> <div class="field">
<label>First Name</label>
<input type="text" name="first-name" placeholder="First Name">
</div> <div class="field">
<label>Last Name</label>
<input type="text" name="last-name" placeholder="Last Name">
</div> <button class="ui button" type="submit">Submit</button>
</form>
(2)form表单 展示错误信息,
<div class="ui form error">
<div class="field">
<label>E-mail</label>
<input type="email" placeholder="joe@schmoe.com">
</div>
<div class="ui error message">
<div class="header">被禁止的行为</div>
<p>只有填入邮件地址,你才能注册帐号</p>
</div>
<div class="ui submit button">Submit</div>
</div>
<div class="ui form">
<div class="two fields">
<div class="field error">
<label>First Name</label>
<input placeholder="First Name" type="text">
</div>
<div class="field">
<label>Last Name</label>
<input placeholder="Last Name" type="text">
</div>
</div>
<div class="field error">
<label>Gender</label>
<div class="ui selection dropdown">
<div class="default text">Select</div>
<i class="dropdown icon"></i>
<input type="hidden" name="gender">
<div class="menu">
<div class="item" data-value="male">Male</div>
<div class="item" data-value="female">Female</div>
</div>
</div>
</div>
<div class="inline field error">
<div class="ui checkbox">
<input type="checkbox" tabindex="0" class="hidden">
<label>我同意本条款和条件</label>
</div>
</div>
</div>
(3)模板过滤器
#只显示comment的错误label <div class="{{ field.errors|yesno:'error, ' }} field">
{{ field.label }}
{{ field }}
</div>
(4)完整html代码
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="{% static 'css/semantic.css'%}" media="screen" title="no title" charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Oswald|Raleway" rel="stylesheet"> <style type="text/css">
.ui.segment.container {
width:700px;
} p {
font-family: 'Raleway', sans-serif;
font-size:18px;
} body {
background:url({% static 'images/star_banner.jpg'%});
background-size:cover;
background-repeat:no-repeat;
background-attachment:fixed
} </style>
</head>
<body>
<div class="ui image">
<img src="" alt="" />
</div>
<div class="ui segment padded container" >
<h1 class="ui header" style="font-family:'Oswald', sans-serif;font-size:40px">
Indonesia pointed at Christmas
</h1>
<p>
his is how it happens:
The most sensible alternative to a life of unbearable hardship is to take a chance on a rubber dinghy in Indonesia pointed at Christmas Island, which is part of Australia. If a refugee survives, this person is not praised for valor but rather ejected 4,000 miles away to another island. Nauru Regional Processing Center. Processing sounds temporary, and it is, in the same way purgatory is temporary. Asylum seekers have been known to wait five years for intercession in the form of a “refugee status determination,” or RSD.
The agony of waiting is what caused the July 2013 riot. RSDs that were promised were not delivered, and asylum seekers protested. They threw rocks at police and lit fire to buildings. No one was hurt, but the fires caused $60 million in damage. It was probably the most power they’d ever wielded. Nauruan police arrested 153 people around 9:30 p.m. and charged them with rioting. But nothing changed. If anything, the detainees were more forlorn than ever.
Depression was becoming rampant. The older children noticed it, and the little ones, too, though they couldn’t quite understand. Something was wrong. Happiness should be easy at that age. But not in Nauru.
Once, a teacher noticed her student searching the ground for something while waiting for the bus to take him home from school. He was a nice little boy. He’d been given something that morning, a sticker. What a thing. But now he’d lost it, and he anxiously combed the dirt and gravel. “Leave it,” the teacher said. “You can find it later.” The boy said nothing. He just slumped into a pile and sobbed.
When the protests of Sept. 30 amounted to nothing, it was as though a reservoir of grief broke through the last levee, and hopelessness flooded the little camp.
All around were thoughts of suicide. One asylum seeker, Yusuf, told his case manager he thought the mood in the camp was worse than ever. A week earlier, the Australian government had taken the unprecedented step of paying Cambodia (as it paid Nauru) to resettle refugees there. The head of the U.N. refugee agency called it “a worrying departure from international norms” because Australia was essentially paying a poor, unsuitable country to take over its own moral and legal obligations. But Cambodia wanted the money, Australia didn’t want the refugees and to this day the plan is still in place.
</p>
</div> <!-- Comments&Form's here -->
<div class="ui segment container" style="width:700px;">
<h3 class="ui header" style="font-family:'Oswald', sans-serif;">Comments</h3>
<div class="ui comments"> {% for comment in comment_list %}
<div class="comment">
<div class="avatar">
<img src="http://semantic-ui.com/images/avatar/small/matt.jpg" alt="" />
</div>
<div class="content">
<a href="#" class="author">{{ comment.name }}</a>
<div class="metadata">
<div class="date">2 days ago</div>
</div>
<p class="text" style="font-family: 'Raleway', sans-serif;">
{{ comment.comment }}
</p>
</div>
</div>
{% endfor %} </div>
<div class="ui divider"></div>
<form class="ui error tiny form" action="" method="post"> {% if form.errors %}
<div class="ui error message">
{{ form.errors }}
</div>
{% for field in form %}
<div class="{{ field.errors|yesno:'error, ' }} field">
{{ field.label }}
{{ field }}
</div>
{% endfor %} {% else %} {% for field in form %}
<div class="field">
{{ field.label }}
{{ field }}
</div>
{% endfor %} {% endif %} {% csrf_token %}
<button type="submit" class="ui blue button" >Click</button>
</form> </div> </body>
</html>
5 Post实现django表单的更多相关文章
- python 全栈开发,Day111(客户管理之 编辑权限(二),Django表单集合Formset,ORM之limit_choices_to,构造家族结构)
昨日内容回顾 1. 权限系统的流程? 2. 权限的表有几个? 3. 技术点 中间件 session orm - 去重 - 去空 inclusion_tag filter 有序字典 settings配置 ...
- python3之Django表单(一)
1.HTML中的表单 在HTML种,表单是在<form>...</form>种的元素,它允许用户输入文本,选择选项,操作对象等,然后发送这些数据到服务器 表单元素允许用户在表单 ...
- django表单的api
django表单的api,参考文档:https://yiyibooks.cn/xx/Django_1.11.6/ref/forms/api.html 绑定与未绑定形式: Form要么是绑定的,要么是未 ...
- Django表单API详解
声明:以下的Form.表单等术语都指的的广义的Django表单. Form要么是绑定了数据的,要么是未绑定数据的. 如果是绑定的,那么它能够验证数据,并渲染表单及其数据,然后生成HTML表单.如果未绑 ...
- 9:django 表单
django自带表单系统,这个表单系统不仅可以定义属性名,还可以自己定义验证,更有自己自带的错误提示系统 这节我们仅仅粗略的来看一下django表单系统的入门运用(具体的实在太多东西,主要是我觉得有很 ...
- django 表单系统 之 forms.Form
继承forms.Form实现django表单系统 参考: https://www.cnblogs.com/zongfa/p/7709639.html https://www.cnblogs.com/c ...
- 关于创建Django表单Forms继承BaseForm的问题
在创建Django表单时,因为需要验证用户输入的验证码是否正确,因此需要在session里提取当前验证码的值和POST提交过来的值进行比对,如图: form.py from django import ...
- Django 表单处理流程
Django 的表单处理:视图获取请求,执行所需的任何操作,包括从模型中读取数据,然后生成并返回HTML页面(从模板中),我们传递一个包含要显示的数据的上下文.使事情变得更复杂的是,服务器还需要能够处 ...
- 第四章:Django表单 - 2:Django表单API详解
声明:以下的Form.表单等术语都指的的广义的Django表单. Form要么是绑定了数据的,要么是未绑定数据的. 如果是绑定的,那么它能够验证数据,并渲染表单及其数据,然后生成HTML表单.如果未绑 ...
- 第四章:Django表单 - 1:使用表单
假设你想从表单接收用户名数据,一般情况下,你需要在HTML中手动编写一个如下的表单元素: <form action="/your-name/" method="po ...
随机推荐
- Quartz Cron表达式的二三事
最近在解决产品上的一个需求,就是定期生成报告(Report),我们叫做Scheduled Report. 原理:UI获取用户输入的时间信息,后台使用Spring框架设置定时任务,这里定时任务用的就是 ...
- Web前端开发规范(二)
3.HTML代码规范 .html文件必须存放在项目工程约定的目录中. .html文件的命名:以模块 + 功能的结合方式来命名,比如:newsList.html. 文档类型声明:HTML4中使用< ...
- seleenium与Vs结合
Vs 自带自动化测试录制工具.selenium则是开源的大众工具.在使用发现vs 自带的工具录制方便,但是修改很难.但是可以提供后续的BUG管理和邮件通知,自动构建等功能.selenium在.net平 ...
- Azure SQL的DTU和eDTU到底是个什么鬼
可以从上表上对应于本地数据库的性能采集的指标,可以估算出应该使用什么样级别的AZURE SQL. 当然服务层选择后仍然可以进行更改. 对于自己应用应该用多大规模的DTU,可以进行详细的评估,可以使用下 ...
- JavaScript(一) 对象基础
1.定义类或对象 1.1 混合的构造函数/原型方法 用构造函数定义对象的所有非函数属性,类似于Java的构造方法.用原型方法定义对象的函数属性(方法).这种方法是使用比较广泛的定义类或对象的方法. / ...
- 百度开源项目插件 - Echarts 图表
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- Ajax使用 初始化数据 + mvc
2017-3-16 mvc+jquery+easyUI做项目 <input type="text" id="txtSTQty" name="tx ...
- BZOJ 4502: 串 AC自动机
4502: 串 Time Limit: 30 Sec Memory Limit: 512 MBSubmit: 195 Solved: 95[Submit][Status][Discuss] Des ...
- hdu-2688 Rotate---树状数组+模拟
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2688 题目大意: 给你n数,(n<=3e6),有两个操作,Q为 当前有多少对数,满足严格递增, ...
- System.Web.UI.HtmlControls
用来创建一个标签.HtmlContainerControl 一般用此类来新建标签. 可能我们熟悉System.Web.UI.WebControls;空间.System.Web.UI.WebContro ...