我试图为用户创建注册页面,但是从Django(v 1.7.1)中获取错误:
失败原因: 未设置CSRF cookie。
我确定,我的电脑上允许使用cookie(Chrome浏览器)。添加{%csrf_token%}并不能解决我的问题。也许有人建议我,如何解决这个问题?
部分来自我的register.html:
<div class="container">
<form action="." class="form-signin" method="post">
{% csrf_token %}
<h4 class="form-signin-heading">Register new user</h4>
{{ form.login }}
{{ form.login.errors }}
{{ form.password }}
{{ form.password.errors }}
{{ form.address }}
{{ form.address.errors }}
{{ form.phone }}
{{ form.phone.errors }}
{{ form.postcode }}
{{ form.postcode.errors }}
{{ form.email }}
{{ form.email.errors }}
<button class="btn btn-small btn-primary" type="submit">Register me</button>
</form>
</div>
RegisterForm.py
# -*- coding: utf-8 -*-
from django import forms
from mainws.models.User import User
class RegisterForm(forms.Form):
login = forms.CharField(min_length=3, max_length=50, required=True,
error_messages={'required': 'Enter login'},
widget=forms.TextInput(attrs={'placeholder': 'login',
'class': "input-block-level"}))
password = forms.CharField(min_length=6, max_length=50, required=True,
error_messages={'required': u'Enter password'},
widget=forms.TextInput(attrs={'placeholder': 'password',
'class': "input-block-level",
'type': 'password'}))
address = forms.CharField(min_length=5, max_length=255, required=True,
error_messages={'required': u'Enter address'},
widget=forms.TextInput(attrs={'placeholder': 'address',
'class': "input-block-level"}))
phone = forms.CharField(min_length=7, max_length=25, required=True,
error_messages={'required': u'Enter phone'},
widget=forms.TextInput(attrs={'placeholder': 'phone',
'class': "input-block-level"}))
postcode = forms.CharField(min_length=2, max_length=25, required=True,
error_messages={'required': u'Enter postcode'},
widget=forms.TextInput(attrs={'placeholder': 'postcode',
'class': "input-block-level"}))
email = forms.EmailField(min_length=5, required=True,
error_messages={'required': u'Enter email'},
widget=forms.TextInput(attrs={'placeholder': 'email',
'class': "input-block-level"}))
def clean(self):
super(RegisterForm, self).clean()
typed_login = self.cleaned_data['login']
if User.objects.filter(login=typed_login).exists():
raise forms.ValidationError('This user already registered!')
return self.cleaned_data
RegisterController.py
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.base import View
from django.shortcuts import render_to_response
from mainws.forms.RegisterForm import RegisterForm
class RegisterController(View):
def get(self, request, *args, **kwargs):
form = RegisterForm()
return render_to_response('user/register.html', locals())
def post(self, request, *args, **kwargs):
form = RegisterForm(request.POST)
if form.is_valid():
#return HttpResponseRedirect('/login')
return HttpResponse('OK!', locals())
else:
return HttpResponse('all not valid!', locals())
答案 0 :(得分:2)
您在render_to_response
中未使用RequestContext的错误。这就是csrf_token为空的原因。
要在您的视图中利用CSRF保护,请按以下步骤操作:
有关详情,请参阅docs。