django - POST 方法总是返回 403 Forbidden

标签 django post csrf django-csrf

我已阅读 Django - CSRF verification failed以及与 django 和 POST 方法相关的几个问题(和答案)。对我来说最好但不工作的答案之一是 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验证失败。

    我有两个问题:
  • 如何修复此错误?
  • 为什么在 django 中做一个“POST”这么难,我的意思是有什么具体的理由让它如此冗长(我来自 PHP,以前从未发现过这样的问题)?
  • 最佳答案

    我可能错了,但是我发现上述解决方案相当复杂。

    对我有用的只是将我的 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/

    相关文章:

    ajax - 如何在ExtJs AjaxRequest中实现CSRFGuard?

    django - csrf token 正在显示?

    ruby-on-rails - 当 api_key 存在时跳过_before_filter

    python - 给用户一个 "reputation system"- 我应该......?

    php - 视频上传,只上传20秒以下的视频

    jquery - Asp.net MVC 5 Ajax POST 在应用程序发布后抛出异常 404(未找到)

    javascript - Angular multipart/form-data 表单发送

    python - 如何验证 django 内联模型管理中不会再次从下拉列表中重新选择项目?

    django - 在 Python 代码中获取静态图片 URL

    python - 从 Python 使用 Spark 所需的库 (PySpark)