我正在使用django 1.10。我在使用POST的表单中有{%csrf_token%}。我使用django registration redux处理注册过程。
在尝试注册新用户时,我收到403错误CSRF验证失败。失败的原因CSRF cookie未设置。 CSRF_COOKIE_SECURE设置为false。
这些是中间件类
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django_user_agents.middleware.UserAgentMiddleware',
]
注册视图
class RegistrationView(FormView):
"""
Base class for user registration views.
"""
disallowed_url = 'registration_disallowed'
form_class = REGISTRATION_FORM
http_method_names = ['get', 'post', 'head', 'options', 'trace']
success_url = None
template_name = 'registration/registration_form.html'
@method_decorator(sensitive_post_parameters('password1', 'password2'))
def dispatch(self, request, *args, **kwargs):
"""
Check that user signup is allowed before even bothering to
dispatch or do other processing.
"""
if not self.registration_allowed():
return redirect(self.disallowed_url)
return super(RegistrationView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
new_user = self.register(form)
success_url = self.get_success_url(new_user)
# success_url may be a simple string, or a tuple providing the
# full argument set for redirect(). Attempting to unpack it
# tells us which one it is.
try:
to, args, kwargs = success_url
except ValueError:
return redirect(success_url)
else:
return redirect(to, *args, **kwargs)
def registration_allowed(self):
"""
Override this to enable/disable user registration, either
globally or on a per-request basis.
"""
return True
def register(self, form):
"""
Implement user-registration logic here.
"""
raise NotImplementedError
def get_success_url(self, user=None):
"""
Use the new user when constructing success_url.
"""
return super(RegistrationView, self).get_success_url()
模板
{% extends "registration/registration_base.html" %}
{% load i18n %}
{% block title %}{% trans "Register for an account" %}{% endblock %}
{% block content %}
<form method="post" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="{% trans 'Submit' %}" />
</form>
{% endblock %}