CSRF 令牌丢失或不正确 [英] CSRF Token missing or incorrect

查看:41
本文介绍了CSRF 令牌丢失或不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是 Django 的初学者,我已经尝试解决这个问题很长时间了.我的中间件类中有django.middleware.csrf.CsrfViewMiddleware",并且我的帖子表单中有令牌.

Beginner at Django here, I've been trying to fix this for a long time now. I do have 'django.middleware.csrf.CsrfViewMiddleware' in my middleware classes and I do have the token in my post form.

这是我的代码,我做错了什么?

Heres my code, what am I doing wrong?

from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from chartsey.authentication.forms import RegistrationForm
from django.template import RequestContext
from django.core.context_processors import csrf

def register(request):

    if request.method == 'POST':
        c = RequestContext(request.POST, {})
        form = RegistrationForm(c)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/")
    else:
        form = RegistrationForm()

    return render_to_response("register.html",  {'form': form,  }, )

这是我的模板:

{% block content %}

    <h1>Register</h1>
    <form action="" method="POST"> {% csrf_token %}
        {{ form.as_p }}
    <input type="submit" value="Submit">
    </form>

{% endblock %}

推荐答案

更新:这个答案来自 2011 年.现在 CSRF 很简单.

这些天你应该使用 render 快捷函数 return render(request, 'template.html') 自动使用 RequestContext 所以下面的建议已经过时了 8 年.

Update: This answer is from 2011. CSRF is easy today.

These days you should be using the render shortcut function return render(request, 'template.html') which uses RequestContext automatically so the advice below is outdated by 8 years.

  1. 使用 render https://docs.djangoproject.com/en/2.2/topics/http/shortcuts/
  2. 添加 CSRF 中间件 https://docs.djangoproject.com/en/2.2/参考/csrf/
  3. 使用{% csrf_token %}模板标签
  4. 确认您看到正在生成的 CSRF 令牌值,并在您的表单请求中提交

原始回复

我的猜测是你在模板中有标签,但它没有呈现任何东西(或者你的意思是你在实际的 HTML 中确认正在生成 CSRF 令牌?)

Original Response

My guess is that you have the tag in the template but it's not rendering anything (or did you mean you confirmed in the actual HTML that a CSRF token is being generated?)

要么使用RequestContext 而不是字典

render_to_response("foo.html", RequestContext(request, {}))

或者确保您的 CONTEXT_PROCESSORS 设置中有 django.core.context_processors.csrf.

Or make sure you have django.core.context_processors.csrf in your CONTEXT_PROCESSORS setting.

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

或者手动将令牌添加到您的上下文中

这篇关于CSRF 令牌丢失或不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆