之前就着手开始尝试用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. B. Vanya and Books( Codeforces Round #308 (Div. 2) 简单题)

    B. Vanya and Books time limit per test 1 second memory limit per test 256 megabytes input standard i ...

  2. C#中使用正则

      using System.Text.RegularExpressions;           private void button1_Click(object sender, EventArg ...

  3. vue - webpack.dev.conf.js for node-portfinder

    描述:获取当前可用的port. (vue-cli配置好了,一旦端口被占用,报错,再次运行时会打开:8080+1,依次类推...8080+n) 官网地址:https://www.npmjs.com/pa ...

  4. 一步一步学Spring.NET——1、Spring.NET环境准备

    Spring.NET 1.3.2下载地址:http://down.51cto.com/data/861700 下载后解压 Spring.NET-1.3.2.7z:这个里面有我们须要用到的全部东西. S ...

  5. 【FinancialKnowledge】拨备

    一句话: 银行拨备就是银行贷款损失减值准备的俗称,其相当于为承担风险和损失的金融资产计提的准备金 通俗易懂的解释见:https://wallstreetcn.com/articles/3307725

  6. RandomForest&ROC

    # -*- coding: utf-8 -*- # __author__ = 'JieYao' from biocluster.agent import Agent from biocluster.t ...

  7. 算法----堆排序(heap sort)

    堆排序是利用堆进行排序的高效算法,其能实现O(NlogN)的排序时间复杂度,详细算法分析能够点击堆排序算法时间复杂度分析. 算法实现: 调整堆: void sort::sink(int* a, con ...

  8. pdo连接mysql操作方法

    PDO常用方法: PDO::query()主要用于有记录结果返回的操作(PDOStatement),特别是select操作. PDO::exec()主要是针对没有结果集合返回的操作.如insert,u ...

  9. springboot文件上传下载,转载的

    Spring Boot入门——文件上传与下载 原文来自:https://www.cnblogs.com/studyDetail/articles/7003253.html 1.在pom.xml文件中添 ...

  10. druid问题记录

    1 {"error":"Instantiation of [simple type, class io.druid.indexing.kafka.supervisor.K ...