之前就着手开始尝试用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方法提交表达的更多相关文章

  1. Django form表单功能的引用(注册,复写form.clean方法 增加 验证密码功能)

    1. 在app下 新建 forms.py 定义表单内容,类型models from django import forms class RegisterForm(forms.Form): userna ...

  2. Django框架之第二篇--app注册、静态文件配置、form表单提交、pycharm连接数据库、django使用mysql数据库、表字段的增删改查、表数据的增删改查

    本节知识点大致为:静态文件配置.form表单提交数据后端如何获取.request方法.pycharm连接数据库,django使用mysql数据库.表字段的增删改查.表数据的增删改查 一.创建app,创 ...

  3. js实现无刷新表单提交文件,将ajax请求转换为form请求方法

    最近在做项目的时候遇到一个需要上传文件的需求,因为ajax请求是无法上传二进制文件流的,所以只能用form表单提交,而form提交有一个问题就是会使页面刷新,本文解决了form表单提交文件时页面刷新的 ...

  4. asp.net.mvc 中form表单提交控制器的2种方法和控制器接收页面提交数据的4种方法

    MVC中表单form是怎样提交? 控制器Controller是怎样接收的? 1..cshtml 页面form提交 (1)普通方式的的提交

  5. form表单提交的方法

    最近研究了下html中,form保单提交的几种方法,现与大家分享一下(注:网上可能已经有好多版本了,这里自己写下来做个总结了,哈!): 方法一:利用form的onsubmit()函数(经常使用) &l ...

  6. python中前后端通信方法Ajax和ORM映射(form表单提交)

    后端从数据库获取数据给到前端: 第一种方式: admin.py文件代码: @admin.route('/showList') def show(): # 获取数据库所有文章数据,得到一个个对象 res ...

  7. 关于form表单提交到Servlet的时候出现tomcat启动错误的解决方法

    1.遇到的问题 今天在写jsp代码的时候通过form表单提交到Servlet的时候出现的tomcat启动错误,琢磨了半天,终于找到了解决方法. 解决问题的关键就在于xml配置的路径和servlet中默 ...

  8. js的form表单提交url传参数(包含+等特殊字符)的解决方法

    方法一:(伪装form表单提交) linkredwin = function(A,B,C,D,E,F,G){        var formredwin = document.createElemen ...

  9. django 使用form组件提交数据之form表单提交

    django的form组件可以减少后台在进行一些重复性的验证工作,极大降低开发效率. 最近遇到一个问题: 当使用form表单提交数据后,如果数据格式不符合后台定义的规则,需要重新在前端页面填写数据. ...

随机推荐

  1. JBoss 系列十七:使用JGroups构建块MessageDispatcher 构建群组通信应用

    内容概要 本部分说明JGroups构建块接口MessageDispatcher,具体提供一个简单示例来说明如何使用JGroups构建块MessageDispatcher 构建群组通信应用 示例描述 构 ...

  2. [Exception Android 22] - Could not find com.android.support:design:23.1.1

    Error:A problem occurred configuring project ':app'. > A problem occurred configuring project ':f ...

  3. RGB和HSL色彩的相互转换

    转自: http://blog.csdn.net/aniven/article/details/2205851 RGB和HSL(也叫HSB/HSV)是两种色彩空间,即:红,绿,蓝(Red,Green, ...

  4. 【VB编程】05.MsgBox与InputBox函数

    在VBA程序中,数据的输入输出是通过函数实现的,其实现的方式是通过对话框的形式表示出来的.例如MsgBox,Inputbox等,不要误认为是输入输出语句的关键字,其实仅仅是一个普通函数而已. [Msg ...

  5. Spring Bean的作用域类型

    Bean的作用域类型 singleton :在Spring IOC容器中仅存在一个Bean实例,Bean以单实例的方式存在; prototype :每次从容器中调用Bean时,都返回一个新的实例,即每 ...

  6. Load和CPU利用率是如何算出来的 (转发)

    本文内容遵从CC版权协议, 可以随意转载, 但必须以超链接形式标明文章原始出处和作者信息及版权声明网址: http://www.penglixun.com/tech/system/how_to_cal ...

  7. angular开发中对请求数据层的封装

    代码地址如下:http://www.demodashi.com/demo/11481.html 一.本章节仅仅是对angular4项目开发中数据请求封装到model中 仅仅是在项目angular4项目 ...

  8. String、StringBuilder、StringBuffer对比

    参考:http://swiftlet.net/archives/1694 http://www.cnblogs.com/springcsc/archive/2009/12/03/1616326.htm ...

  9. Navicat Premium 快捷键

    1.ctrl+q 打开查询窗口2.ctrl+/ 注释sql语句3.ctrl+shift +/ 解除注释4.ctrl+r 运行查询窗口的sql语句5.ctrl+shift+r 只运行选中的sql语句6. ...

  10. myeclipse的user library不自动部署到WEB-INF/lib目录下的解决办法

    右键进入项目属性 Properties 点进去 左边 MyEclipse -> Deployment Assembly 右边 Add -> JavaBuild Path Entries - ...