CSRF令牌丢失或在

2024-05-01 21:54:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Django的初学者,我已经试了很长时间了。 我的中间件类中有'django.middleware.csrf.CsrfViewMiddleware',我的post表单中也有这个标记。

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

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 %}

Tags: todjangofromimportformregisterresponserequest
3条回答

尝试使用“渲染”而不是“渲染到”响应:

from django.shortcuts import render

render(request, "foo.html", {})

Django - what is the difference between render(), render_to_response() and direct_to_template()?

如上链接所述,它在Django 1.3中引入,并自动使用RequestContext

只需将此添加到您的视图中

return render_to_response("register.html", {'form': form, }, context_instance = RequestContext(request))

它会起作用的!!

更新:这个答案来自2011年。CSRF今天很容易

现在您应该使用render快捷方式函数return render(request, 'template.html'),它自动使用RequestContext,因此下面的建议将过期8年。

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

原始回复

我的猜测是您在模板中有标记,但它没有呈现任何内容(或者您是说您在实际的HTML中确认了CSRF令牌正在生成?)

使用RequestContext而不是字典

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

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

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

Or add the token to your context manually

相关问题 更多 >