【问题标题】:Forbidden (403) CSRF verification failed. Request aborted.in Django禁止 (403) CSRF 验证失败。请求 aborted.in Django
【发布时间】:2018-06-06 08:27:07
【问题描述】:

为什么 Django 会显示此错误:'Forbidden (403)CSRF 验证失败。请求中止。当我的表单中已经有{% csrf_token %} 时。

templates/core/signup.html

{% block content %}
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Sign up</button>
    </form>
{% endblock %}

views.py

from django.contrib.auth.forms import UserCreationForm 
from django.views.generic.edit import CreateView 

class SignUpView(CreateView): 
    template_name = 'core/signup.html' 
    form_class = UserCreationForm

【问题讨论】:

    标签: python django django-forms django-csrf


    【解决方案1】:

    在您的views.py 中,您需要在render_to_response 中传递RequestContext 才能真正运行上下文处理器。

    from django.template import RequestContext
    
     context = {}
     return render_to_response('my_template.html',
                               context,
                               context_instance=RequestContext(request))
    

    新的渲染快捷方式(django 1.3+)将为您完成:

    from django.shortcuts import render
    
     context = {}
     return render(request, 'my_template.html', context)
    

    对于class-based view:

    class MyFormView(View):
         form_class = MyForm
         initial = {'key': 'value'}
         template_name = 'form_template.html'
    
         def post(self, request, *args, **kwargs):
             form = self.form_class(request.POST)
             if form.is_valid():
                 # <process form cleaned data>
                 return HttpResponseRedirect('/success/')
    
             return render(request, self.template_name, {'form': form})
    

    【讨论】:

    • 如何在基于类的视图中做到这一点?
    • 我需要看看你的意见。我会更容易回答你。
    • @djangolearner 不要在 cmets 中发布代码,它难以辨认。将其添加到您的问题的编辑中。
    • @RohanBaddi 至少在 CBV 中你不需要重新定义 post 方法,而且 csrf_token 也不需要它来工作。
    • @guillermo chamorro 在回复某人docs.djangoproject.com/en/2.0/topics/class-based-views/intro/…之前先做你的研究
    【解决方案2】:

    因为您已经将 csrf 令牌从 django.core.context_processors.csrf 传递给上下文管理器。检查表单 HTML 是否有这样的内容:

    &lt;input type='hidden' name='csrfmiddlewaretoken' value="jqhdwjavwjagjzbefjwdjqlkkop2j3ofje" /&gt;

    要使 csrf 保护起作用,还需要做一些其他的事情(查看docs):

    • 您的浏览器必须接受来自您服务器的 cookie

    • 确保在 settings.py 中包含“django.middleware.csrf.CsrfViewMiddleware”作为中间件(或者在要保护的特定视图上使用装饰器 csrf_protect())

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-05
      • 2016-08-27
      • 2017-06-26
      • 2014-11-15
      • 2019-07-22
      • 2016-05-12
      • 2017-08-06
      相关资源
      最近更新 更多