简体   繁体   English

禁止(403)CSRF验证失败。 请求中止。在Django中

[英]Forbidden (403) CSRF verification failed. Request aborted.in Django

Why does Django show this error: 'Forbidden (403)CSRF verification failed. Django为什么显示此错误:'禁止(403)CSRF验证失败。 Request aborted.' 请求中止。 when I already have {% csrf_token %} in the form. 当我已经有{% 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

Since you are already passing on the csrf token from django.core.context_processors.csrf to the context manager. 由于您已经将csrf令牌从django.core.context_processors.csrf传递到上下文管理器。 Check whether the form HTML has something like this or not: 检查表单HTML是否具有以下内容:

<input type='hidden' name='csrfmiddlewaretoken' value="jqhdwjavwjagjzbefjwdjqlkkop2j3ofje" />

A couple of other things are required to make the csrf protection work (check out the docs ): 要使csrf保护起作用,还需要执行其他一些操作(请参阅docs ):

  • Your browser has to accept cookies from your server 您的浏览器必须接受服务器中的Cookie

  • Make sure you have 'django.middleware.csrf.CsrfViewMiddleware' included as middleware in your settings.py (alternatively use the decorator csrf_protect() on particular views you want to protect) 确保您的settings.py中已将“ django.middleware.csrf.CsrfViewMiddleware”作为中间件包括在内(或者在要保护的特定视图上使用装饰器csrf_protect())

In your views.py you need to pass the RequestContext in your render_to_response for the context processors to actually be run. 在views.py中,您需要在render_to_response传递RequestContext才能真正运行上下文处理器。

from django.template import RequestContext

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

the new render shortcut (django 1.3+) will do it for you: 新的渲染快捷方式(django 1.3+)将为您完成此操作:

from django.shortcuts import render

 context = {}
 return render(request, 'my_template.html', context)

For class-based view : 对于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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM