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 ...
随机推荐
- 浅谈SQL Server中的事务日志(一)----事务日志的物理和逻辑构架
简介 SQL Server中的事务日志无疑是SQL Server中最重要的部分之一.因为SQL SERVER利用事务日志来确保持久性(Durability)和事务回滚(Rollback).从而还部分确 ...
- Linux目录配置——Linux目录配置标准:FHS
事实上,FHS针对目录树架构仅定义出三层目录下应该放置哪些数据,分别是下面三个目录: 一./(根目录):与开机系统有关 根目录(/)所在分区应该越小越好,且应用程序所安装的软件最好不要与根目录放在同一 ...
- oracle 创建SDO_Geometry表
Oracle Spatial由一坨的对象数据类型,类型方法,操作子,函数与过程组合而成.一个地理对象作为一个SDO_GEOMETRY对象保存在表的一个字段里.空间索引则由普通的DDL和DML语句来建立 ...
- hdu-2688 Rotate---树状数组+模拟
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2688 题目大意: 给你n数,(n<=3e6),有两个操作,Q为 当前有多少对数,满足严格递增, ...
- Android(java)学习笔记60:继承中父类 没有无参构造
1. 继承中父类 没有无参构造: package com.himi.test1; /* 如果父类没有无参构造方法,那么子类的构造方法会出现什么现象呢? 报错. 如何解决呢? A:在父类中加一个无参构造 ...
- list 用法的随手记
在list 用法中.1. add是直接添加 一个变量.不能添加一个 集合元素,比如数组 这种写法是错误的 ,因为不能添加集合 这种写法是对的,因为直接添加元素 2. 但是addrannge 是添加一个 ...
- Advanced Memory Allocation 内存分配进阶[转]
May 01, 2003 By Gianluca Insolvibile in Embedded Software Call some useful fuctions of the GNU C l ...
- js获取对象所有的keys
Js中获取对象的所有key值 假如现在有一个对象 var obj = { A:2 ,B:"Ray" ,C:true ,D:function(){} } 如果想遍历对象obj中的 ...
- MyBatis中解决字段名与实体类属性名不相同的冲突
一: 通过在查询的sql语句中定义字段名的别名,让字段名的别名和实体类的属性名一致,这样就可以表的字段名和实体类的属性名一一对应上了,这种方式是通过在sql语句中定义别名来解决字段名和属性名的映射关系 ...
- 第15章 RCC—使用HSE/HSI配置时钟—零死角玩转STM32-F429系列
第15章 RCC—使用HSE/HSI配置时钟 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku. ...