當我嘗試註冊,我得到一個錯誤:Django的csrf_token失蹤錯誤
Forbidden (403) CSRF verification failed. Request aborted.
我的代碼:
@csrf_protect
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data.get("firstname")
last_name = form.cleaned_data.get("lastname")
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = User.objects.create_user(username=username,password=password)
user.first_name = first_name
user.last_name = last_name
user.set_password(password)
user.is_active = True
user.save()
return HttpResponseRedirect('/home/')
else:
form = RegistrationForm()
return render_to_response('registration/registerHome.html',dict(form=form,
context_instance=RequestContext(request)))
我form.py
class RegistrationForm(forms.Form):
"""
A registration form to create normal user.
"""
firstname = forms.RegexField(regex=r'^\[a-zA-Z]+$',
widget=forms.TextInput(attrs={ 'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'First Name' }),
error_messages={ 'invalid': _("Only alphabets are allowed.") }
)
lastname = forms.RegexField(regex=r'^\[a-zA-Z]+$',
widget=forms.TextInput(attrs={ 'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'Last Name' }),
error_messages={ 'invalid': _("Only alphabets are allowed.") }
)
username = forms.RegexField(regex=r'^\w+$',
widget=forms.TextInput(attrs={'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'username'}),
error_messages={ 'invalid': _("Only [a-z A-Z 0-9 _] are allowed.") }
)
password = forms.CharField(widget=forms.PasswordInput(attrs={
'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'password',
'render_value':False })
)
def clean_username(self):
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_("Username already exists."))
class Meta:
model = User
我template.html
<form action="." method="post" role="form" id="register-form">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit" />
</form>
有人請幫助我,爲什麼我得到一個錯誤。我試圖解決這個問題1周,但仍然出現錯誤。請幫幫我。
你確定CsrfViewMiddleware在你的設置文件中添加? – dentemm
是的。 'django.middleware.csrf.CsrfViewMiddleware',在setting.py – ecoder