djangoPOST表单的使用

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

环境如下:django 1.7.8 版本.

1.在POST表单的时候会出现这个错误提示.

禁止访问 (403)

CSRF验证失败. 相应中断.

Help

Reason givenforfailure:

CSRF token missingorincorrect.

In general, this can occur when thereisa genuine Cross Site Request Forgery,orwhen Django's CSRF mechanism has not been used correctly.

For POST forms, you need to ensure:Your browserisaccepting cookies.

The view function passes a request to the template's render method.In the template, thereisa {% csrf_token %} template tag inside each POST form that targets an internal URL.

If you arenotusing 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.

无耐.看上面的提示是防止CSRF.也就是安全方面的,防止跨站请求伪造.

根据上面的提示来.需要有{% csrf_token %},那就在from表单中添加下

添加后的html代码如下.

{% extends"base.html"%}

{% block title %}

hello

{% endblock %}

{% block content %}<divclass="container">

<formclass="form-signin"action="/login_webmail/"method='post'>{% csrf_token %}<h2class="form-signin-heading">Please signin</h2>

<labelclass="sr-only"for="inputUserName">Email address/UserName</label>

<input type="text"autofocus=""required=""placeholder="Email address/UserName"class="form-control"id="inputUserName"name="inputUserName">

<labelclass="sr-only"for="inputPassWord">Password</label>

<input type="password"required=""placeholder="Password"class="form-control"id="inputPassword">

<divclass="checkbox">

<label>

<input type="checkbox"value="remember-me">Remember me</label>

</div>

<button type="submit"class="btn btn-lg btn-primary btn-block">Signin</button>

</form>

</div> <!-- /container -->{% endblock %}

重点是from后面的{% csrf_token %}

根据官网的提示及百度.

views.py的代码更改如下,主要的是return render_to_response('index.html',context_instance=RequestContext(request))

后面的 **context_instance=RequestContext(request)**

fromdjango.httpimportHttpResponseimportdatetimefromdjango.shortcutsimportrender_to_response#postfromdjango.templateimportRequestContext#postdefwebindex(request):returnrender_to_response('index.html',context_instance=RequestContext(request))

接收的views视图方法

deflogin_webmail(request):if'inputUserName'inrequest.POST:

message= request.POST['inputUserName']else:

message="Not inputUserName"returnrender_to_response('test_post.html',{'test_post_name':message})

再测试.是否OK了.总结.只有两个步骤.

1.在from 表单中添加 {% csrf_token %}

2.在视图中添加 from django.template import RequestContext 导入项,并且在return 返回中添加context_instance=RequestContext(request)

然后就OK了.看来也是很简单的.新手可以参考.

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航