CSRF令牌丢失或不正确 [英] CSRF Token missing or incorrect
问题描述
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 %}
推荐答案
p>我的猜测是,你在模板中有标签,但它没有呈现任何内容(或者您是否意味着您在实际的HTML中确认生成了CSRF令牌?)
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, {}))
或确保你有 django.core.context_processors.csrf
在您的 CONTEXT_PROCESSORS
设置。
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屋!