禁止(403)CSRF验证失败。请求aborted.in Django

问题描述 投票:1回答:2

为什么Django显示此错误:'禁止(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
2个回答
0
投票

因为您已经将django.core.context_processors.csrf中的csrf标记传递给上下文管理器。检查表单HTML是否具有以下内容:

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

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

  • 您的浏览器必须接受来自您服务器的cookie
  • 确保你的settings.py中包含'django.middleware.csrf.CsrfViewMiddleware'作为中间件(或者在想要保护的特定视图上使用装饰器csrf_protect())

-1
投票

在views.py中,您需要在RequestContext中传递render_to_response,以便实际运行上下文处理器。

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})
© www.soinside.com 2019 - 2024. All rights reserved.