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 ...
随机推荐
- BarCode条形码生成库
一.Barcode生成条形码的类库 二.示例 新建mvc空项目,添加Nuget引用 主要代码 // // GET: /Home/ public FileContentResult Index() { ...
- Linux读取NTFS类型数据盘
Windows的文件系统通常使用NTFS或者FAT32格式,而Linux的文件系统格式通常是EXT系列,请参考下面方法: 1) 在Linux系统上使用以下命令安装ntfsprogs软件使得Linux能 ...
- TP5.1:模板继承(重要知识点)
1.在app\index\controller文件夹新建一个名为Lyot(自定义)的控制器,在控制器中定义: 2.创建一个被继承的public(自定义)文件夹,里面有三个文件,分别是header.ht ...
- QT学习之QPair类
#QPair类 QPair是一个用来存储一对对象的容器模板.其有两个值,first和second. QPair() QPair(const T1 & value1, const T2 & ...
- Oracle 日期加减运算
-- Start 我们都知道数字可以进行加.减.乘.除等运算.那么,日期可不可以呢?答案是,日期只能进行加.减运算. 在开始操作日期之前,我们先了解一下 Oracle 支持哪些日期数据类型,如下所示: ...
- POJ - 3109 Inner Vertices
不存在-1的情况,而且最多一轮就结束了.如果新增加的黑点v0会产生新的黑点v1,那么v0和v1肯定是在一条轴上的,而原来这条轴上已经有黑点了. 离散以后扫描线统计,往线段上插点,然后查询区间上点数. ...
- 前端高质量知识(三)-JS变量对象详解
在JavaScript中,我们肯定不可避免的需要声明变量和函数,可是JS解析器是如何找到这些变量的呢?我们还得对执行上下文有一个进一步的了解. 在上一篇文章中,我们已经知道,当调用一个函数时(激活), ...
- hiho 第135周 九宫
题目链接:http://hihocoder.com/contest/hiho135/problem/1 由于是九宫格,全排列也就是9! (362880)种方式,我就直接暴力枚举排列好了. #inclu ...
- Poj(2240),Floyd求汇率是不是赚钱
题目链接:http://poj.org/problem?id=2240. Floyd算法修改一下,我要最大路径(通过转汇率变到最大)改成max. #include <iostream> # ...
- P1069 细胞分裂
P1069 细胞分裂 考虑质因数分解 先将m1,质因数分解后再根据数学定理将所有质数的质数全乘m2 然后将输入的数据相同处理,再判断 顺便说一下判断规矩 1肯定不行 如果分解后有没有m1质因数分解中的 ...