POST方法总是返回403禁止 [英] POST method always return 403 Forbidden
问题描述
我已阅读 Django - CSRF验证失败以及与此相关的几个问题(和答案) django和POST方法。我最好的但不是工作的答案之一是 https://stackoverflow.com/a/4707639/755319
I have read Django - CSRF verification failed and several questions (and answers) related to django and POST method. One of the best-but-not-working-for-me answer is https://stackoverflow.com/a/4707639/755319
所有批准的答案建议至少3件事:
All of the approved answers suggest at least 3 things:
- 使用RequestContext作为render_to_response_call的第三个参数
- 使用POST方法在每个窗体中添加{%csrf_token%}
- 检查settings.py中的MIDDLEWARE_CLASSES我已经完全按照建议完成了,但是错误仍然出现在这个文件夹里。
我使用django 1.3.1(从ubuntu 12.04仓库)和python 2.7(默认从ubuntu)
I've done exactly as suggested, but the error still appeared. I use django 1.3.1 (from ubuntu 12.04 repository) and python 2.7 (default from 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):
and this is my template (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验证失败。
I've restarted the server, but the 403 forbidden error is still there, telling that CSRF verification failed.
我有两个问题:
- 如何解决这个错误?
- 为什么在django中设置POST是很困难的,我的意思是有什么具体的理由让它如此冗长(我来自PHP,从来没有发现这样的问题)?
推荐答案
尝试将RequestContext放在search_form中view的render_to_response:
Try putting RequestContext in the search_form view's render_to_response:
context_instance=RequestContext(request)
这篇关于POST方法总是返回403禁止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!