我读过了Django - CSRF 验证失败 https://stackoverflow.com/questions/4547639/django-csrf-verification-failed以及与 django 和 POST 方法相关的几个问题(和答案)。最好但不适合我的答案之一是https://stackoverflow.com/a/4707639/755319 https://stackoverflow.com/a/4707639/755319
所有获得批准的答案至少表明了三件事:
- 使用RequestContext作为render_to_response_call的第三个参数
- 使用 POST 方法在每个表单中添加 {% csrf_token %}
- 检查settings.py中的MIDDLEWARE_CLASSES
我完全按照建议做了,但错误仍然出现。我使用 django 1.3.1(来自 ubuntu 12.04 存储库)和 python 2.7(默认来自 ubuntu)
这是我的观点:
# Create your views here.
from django.template import RequestContext
from django.http import HttpResponse
from django.shortcuts import render_to_response
from models import BookModel
def index(request):
return HttpResponse('Welcome to the library')
def search_form(request):
return render_to_response('library/search_form.html')
def search(request):
if request.method=='POST':
if 'q' in request.POST:
q=request.POST['q']
bookModel = BookModel.objects.filter(title__icontains=q)
result = {'books' : bookModel,}
return render_to_response('library/search.html', result, context_instance=RequestContext(request))
else:
return search_form(request)
else:
return search_form(request)
这是我的模板(search_form.html):
{% extends "base.html" %}
{% block content %}
<form action="/library/search/" method="post">
{% csrf_token %}
<input type="text" name="q">
<input type="submit" value="Search">
</form>
{% endblock %}
我已经重新启动了服务器,但是403禁止错误仍然存在,告诉CSRF验证失败。
我有 2 个问题:
- 如何修复这个错误?
- 为什么在 django 中创建“POST”如此困难,我的意思是有什么具体原因使其如此冗长(我来自 PHP,以前从未发现过这样的问题)?
我可能错了,但我发现上述解决方案相当复杂。
对我有用的只是将我的 csrf 令牌包含到我的发布请求中。
$.ajax({
type: "POST",
url: "/reports/",
data: { csrfmiddlewaretoken: "{{ csrf_token }}", // < here
state:"inactive"
},
success: function() {
alert("pocohuntus")
console.log("prototype")
}
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)