我读过Django - CSRF验证失败,以及与django和POST方法相关的几个问题(和答案).其中一个最好但不能正常工作的答案是/sf/ask/17360801/
所有批准的答案都表明至少有三件事:
使用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 %}
{% csrf_token %}
{% endblock %}
我重新启动了服务器,但403禁止错误仍然存在,告诉CSRF验证失败.
我有两个问题:
如何解决这个错误?
为什么在django中制作"POST"这么难,我的意思是有任何特定的理由让它变得如此冗长(我来自PHP,以前从未发现过这样的问题)?