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 (403) 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都没法翻过去了,真实坑死了我们这群苦逼民工。

 

posted @ 2015-08-23 00:06  forilen  阅读(393)  评论(0编辑  收藏  举报