django form POST方法提交表达
之前就着手开始尝试用django来简化web开发的流程周期,果不其然,速度还行,当然前期的产品那就相当粗糙了。举例来说,就连最基本的登录都是抄别人的,最可怕的是用GET方法提交表单,今天就尝试解决这个问题,用POST方法来提交登录数据。
做过web开发的都知道相对而言,POST方法比GET方法更安全,真的是这样么?
下面先具体说明如何用GET方法提交表单:
template模板代码:
<form id="login" class="form-horizontal" role="form" action="/login" method="get" onSubmit="return validate_form(this)">
<div class="form-group" >
<div class="login-l"><label for="username" class="col-sm-2 control-label">用户名</label></div>
<div class="col-sm-2 login-r" >
<input type="text" class="form-control" id="username" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="login-l"><label for="inputPassword3" class="col-sm-2 control-label">密码</label></div>
<div class="col-sm-2 login-r">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
</div>
<div class="form-group" >
<div class="col-sm-offset-2 col-sm-10" >
<div class="checkbox">
<label>
<input type="checkbox"> 记住我
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10" >
<button type="submit" class="btn btn-default" >登录</button>
{% if error %}
<font color="red">{{ error }}</font>
{% endif %}
</div>
</div>
</form>
views.py逻辑处理代码:
from django.shortcuts import render_to_response
from django.contrib import auth def index(request):
# current_date=datetime.datetime.now()
if request.user.is_authenticated():
'if the session remains , auto login'
return render_to_response('srvMonitor/srvstatus.html')
else:
return render_to_response('login.html') def login(request):
username = request.GET.get('username')
password = request.GET.get('password')
User = auth.authenticate(username=username, password=password) if User is not None and User.is_active:
auth.login(request, User)
return render_to_response('srvMonitor/srvstatus.html')
else:
return render_to_response('login.html', {'error': "用户名密码错误"})
get方法来提交表单在settings.py中基本没啥很多需要配置的。
下面再说下如何用POST方法来提交表单,如果在上面代码的基础上直接把模板中的提交方法从GET改为POST,必定会报下面的错误:
Forbidden () CSRF verification failed. Request aborted.Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly.
For POST forms, you need to ensure: Your browser is accepting cookies. The view function uses RequestContext for the template,
instead of Context. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag,
as well as those that accept the POST data. You're seeing the help section of this page because you have DEBUG = True in your Django settings file.
Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting.
从报错中可以看出需要配置三个地方:
1. settings.py需要设置:APPEND_SLASH = False
2. 提交表单的form中需要添加 {% csrf_token %}
3. 处理提交表达逻辑中需要添加修饰符 @csrf_protect, 跳转需要添加 context_instance=RequestContext(request)
也就是下面的几项:
template模板代码:
<form id="login" class="form-horizontal" role="form" action="/login" method="post" onSubmit="return validate_form(this)">
{% csrf_token %}
<div class="form-group" >
<div class="login-l"><label for="username" class="col-sm-2 control-label">用户名</label></div>
<div class="col-sm-2 login-r" >
<input type="text" class="form-control" id="username" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="login-l"><label for="inputPassword3" class="col-sm-2 control-label">密码</label></div>
<div class="col-sm-2 login-r">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
</div>
<div class="form-group" >
<div class="col-sm-offset-2 col-sm-10" >
<div class="checkbox">
<label>
<input type="checkbox"> 记住我
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10" >
<button type="submit" class="btn btn-default" >登录</button>
{% if error %}
<font color="red">{{ error }}</font>
{% endif %}
</div>
</div>
</form>
views.py逻辑代码:
from django.contrib import auth
from django.views.decorators.csrf import csrf_protect def index(request):
# current_date=datetime.datetime.now()
if request.user.is_authenticated():
'if the session remains , auto login'
return render_to_response('srvMonitor/srvstatus.html')
else:
return render_to_response('login.html',
context_instance=RequestContext(request)) @csrf_protect
def login(request):
username = request.POST.get('username')
password = request.POST.get('password')
User = auth.authenticate(username=username, password=password) if User is not None and User.is_active:
auth.login(request, User)
return render_to_response('srvMonitor/srvstatus.html')
else:
return render_to_response('login.html', {'error': "用户名密码错误"},
context_instance=RequestContext(request))
settings.py配置代码:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
APPEND_SLASH = False
这个还是比较简单的,主要是找网上的那些资料真心不容易,某墙前几天连honxi都没法翻过去了,真实坑死了我们这群苦逼民工。
django form POST方法提交表达的更多相关文章
- Django form表单功能的引用(注册,复写form.clean方法 增加 验证密码功能)
1. 在app下 新建 forms.py 定义表单内容,类型models from django import forms class RegisterForm(forms.Form): userna ...
- Django框架之第二篇--app注册、静态文件配置、form表单提交、pycharm连接数据库、django使用mysql数据库、表字段的增删改查、表数据的增删改查
本节知识点大致为:静态文件配置.form表单提交数据后端如何获取.request方法.pycharm连接数据库,django使用mysql数据库.表字段的增删改查.表数据的增删改查 一.创建app,创 ...
- js实现无刷新表单提交文件,将ajax请求转换为form请求方法
最近在做项目的时候遇到一个需要上传文件的需求,因为ajax请求是无法上传二进制文件流的,所以只能用form表单提交,而form提交有一个问题就是会使页面刷新,本文解决了form表单提交文件时页面刷新的 ...
- asp.net.mvc 中form表单提交控制器的2种方法和控制器接收页面提交数据的4种方法
MVC中表单form是怎样提交? 控制器Controller是怎样接收的? 1..cshtml 页面form提交 (1)普通方式的的提交
- form表单提交的方法
最近研究了下html中,form保单提交的几种方法,现与大家分享一下(注:网上可能已经有好多版本了,这里自己写下来做个总结了,哈!): 方法一:利用form的onsubmit()函数(经常使用) &l ...
- python中前后端通信方法Ajax和ORM映射(form表单提交)
后端从数据库获取数据给到前端: 第一种方式: admin.py文件代码: @admin.route('/showList') def show(): # 获取数据库所有文章数据,得到一个个对象 res ...
- 关于form表单提交到Servlet的时候出现tomcat启动错误的解决方法
1.遇到的问题 今天在写jsp代码的时候通过form表单提交到Servlet的时候出现的tomcat启动错误,琢磨了半天,终于找到了解决方法. 解决问题的关键就在于xml配置的路径和servlet中默 ...
- js的form表单提交url传参数(包含+等特殊字符)的解决方法
方法一:(伪装form表单提交) linkredwin = function(A,B,C,D,E,F,G){ var formredwin = document.createElemen ...
- django 使用form组件提交数据之form表单提交
django的form组件可以减少后台在进行一些重复性的验证工作,极大降低开发效率. 最近遇到一个问题: 当使用form表单提交数据后,如果数据格式不符合后台定义的规则,需要重新在前端页面填写数据. ...
随机推荐
- web 表单,脚本验证
1.不能含有中文 var obj = document.form1.txtName.value; if(/.*[\u4e00-\u9fa5]+.*$/.test(obj)) { alert(" ...
- gensim自然语言处理(续)
上一篇,已经实现了如何将一条语句在一个语料库中比较相似度, 发现运行的时候每次都要编译语料库,通过查找资料,可以一次性编译成预料库,存人文件 编译语料库代码 11_k.py import sysimp ...
- 【Linux】配置JAVA_HOME环境变量
1. 永久修改,对所有用户有效 # vi /etc/profile //按键盘[Shift + g], 在profile文件最后添加下面的内容: export JAVA_HOME = /home/my ...
- win10下Visual Studio 2015,C++ x64编译zmq
PS.本人编译过程踩得坑,记录备忘 下载:(1)官网:http://zeromq.org/intro:get-the-software,有简明的编译方式,cmake的,这里不多赘述 (2)到GitHu ...
- Linux内核分析:实验八--Linux进程调度与切换
刘畅 原创作品转载请注明出处 <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 概述 这篇文章主要分析Li ...
- 服务器如何开启php的fsockopen函数? 使用发邮箱类
参考:http://www.daixiaorui.com/read/16.html#viewpl 服务器如何开启php的fsockopen函数?如果你要使用一些邮件的类,那么很多要求支持php的fso ...
- jumpserver v0.5.0 创建用户和管理机器
用户管理-创建用户 data 用户详情 如下 创建用户组 data 资产列表添加资产 jumpserver 的 root 公钥需保持到 后端服务器的 authorized_keys 里, 然后测 ...
- newWindow 弹出的新窗口居中显示
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
- jqchart 使用的几点小技巧
官网demo地址:http://www.jqchart.com/jquery/chart 简单示例: [javascript] $('#jqChart').jqChart({ title: 'jqCh ...
- unity, unity中GL.MultMatrix的一个超级bug
GL.MultMatrix与OpenGL固定管线的glMultMatrix函数行为并不一致,不是累乘,而是覆盖. 例如下面例子,本来预期是在(100,100)处画一个方块,而实际效果却是在(0,0)处 ...