我已阅读Django - CSRF verification failed以及与django和POST方法有关的几个问题(和答案)。其中最好的,但并非工作换我的答案是https://stackoverflow.com/a/4707639/755319POST方法总是返回403 Forbidden
所有经批准的答案建议至少三件事情:
- 使用的RequestContext作为render_to_response_call
- 添加的第三个参数{%csrf_token%}与POST方法
- 各种形式的检查MIDDLEWARE_CLASSES settings.py中
我究竟做的建议,但错误依然出现了。我使用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,之前从未发现过这样的问题)?
那的作品,谢谢您的回答。 但是如何以及为什么?你能解释一下吗? – goFrendiAsgard
https://docs.djangoproject.com/zh/dev/ref/contrib/csrf/#how-to-use-it - 阅读要点#3 – zubinmehta
由于'csrf_token'必须在您的视图中创建,因此django可以通过它的模板。在你的情况下,由于你的搜索视图不会创建一个标记,所以你的模板中的'{%csrf_token%}'是'空字符串(None)'并且结果页验证失败 – FallenAngel