之前就着手开始尝试用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. kindeditor 图片上传插件

    富文本编辑器,kindeditor是比较好用的一款.需要的功能都有,文档.demo也详细.有什么功能去官网看一眼就好. 官网:http://kindeditor.net/ 一些好用的如图片上传,kin ...

  2. python中,== 与 is 之间区别

    在python中,== 与 is 之间既有区别,又有联系,本文将通过实际代码的演示,力争能够帮助读到这篇文章的朋友以最短的时间理清二者的关系,并深刻理解它们在内存中的实现机制. 扯淡的话不多说,下面马 ...

  3. 饿了么ui添加事件

    最近饿了么ui挺火,连美团都有项目组再用,刚好最近项目重构,就引入了进来,刚用上就发现一个大坑,在配合vue使用时,居然无法添加自定义事件 找了半天才发现原因是需要在事件后面加上  ‘’.native ...

  4. FPS计算New

    using UnityEngine; using System.Collections; public class CarGUI : MonoBehaviour { private const flo ...

  5. Unity3d_ADBannerView

    原地址:http://blog.csdn.net/cynixway/article/details/7686393 ADBnnerView提供对Apple iAd框架中ADBannerView的包中, ...

  6. ionic 图片加载失败,显示默认图片代替

    1.首先编写自定义指令 angular.module('starter.directives', []) //当图片找不到事显示替代图片 .directive("errSrc", ...

  7. Visual studio之C# 调用系统软键盘(外部"osk.exe")

    背景 App需要调用系统软键盘输入数据,自己去实现软键盘有些复杂,现在又是急需,没时间去研究实现软键盘,所以只能调用系统软键盘. 正文 需要添加命名空间, using System.Diagnosti ...

  8. LaTex的注释

    在LaTex中的注释有以下3种 1.注释一行:使用%注释一行文字, 在%后的文字都不予编译: 2.注释一段:使用\iffalse .... \fi 包含一段文字,被包含的文字被注释掉了: 3.注释一段 ...

  9. 动态规划初级 入门理解 C#代码

      using System; using System.Collections.Generic; using System.Linq; using System.Text; using Micros ...

  10. 深度学习之Matlab 转C++在iOS上測试CNN手型识别

    1 前言 在上一篇Blog.我介绍了在iOS上执行CNN的一些方法. 可是,一般来说.我们须要一个性能强劲的机器来跑CNN,我们仅仅只是须要将得到的结果用于移动端. 之前在Matlab使用UFLDL的 ...