我已阅读 Django - CSRF verification failed以及与 django 和 POST 方法相关的几个问题(和答案)。对我来说最好但不工作的答案之一是 https://stackoverflow.com/a/4707639/755319
所有批准的答案都至少表明了三件事:
我完全按照建议做了,但错误仍然出现。我使用 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验证失败。
我有两个问题:
最佳答案
我可能错了,但是我发现上述解决方案相当复杂。
对我有用的只是将我的 csrf token 包含到我的发布请求中。
$.ajax({
type: "POST",
url: "/reports/",
data: { csrfmiddlewaretoken: "{{ csrf_token }}", // < here
state:"inactive"
},
success: function() {
alert("pocohuntus")
console.log("prototype")
}
})
关于django - POST 方法总是返回 403 Forbidden,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10663446/