Python django中的自定义用户注册问题
我正在使用python和django开发一个web应用程序,其中我构建了一个扩展用户模型的CustomUser模型,还构建了一个注册表单。但问题是,每次我注册一个新用户时,当我返回登录页面并输入用户名和密码时,它总是给出“用户名和密码不匹配”的消息 我在这里粘贴代码: forms.pyPython django中的自定义用户注册问题,python,django,Python,Django,我正在使用python和django开发一个web应用程序,其中我构建了一个扩展用户模型的CustomUser模型,还构建了一个注册表单。但问题是,每次我注册一个新用户时,当我返回登录页面并输入用户名和密码时,它总是给出“用户名和密码不匹配”的消息 我在这里粘贴代码: forms.py import re from django.utils.translation import ugettext_lazy as _ from django import
import re
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from models import CustomUser
import pdb
class RegistrationForm(UserCreationForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
first_name = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("First name"), error_messages={ 'invalid': _("This value must contain only letters") })
last_name = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Last name"), error_messages={ 'invalid': _("This value must contain only letters") })
password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password"))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)"))
date_of_birth = forms.DateField(widget=forms.TextInput(attrs= {'class':'datepicker'}))
sex = forms.ChoiceField(choices=(('M', 'MALE'), ('F', 'FEMALE')), label=_("Sex"))
voter_id = forms.CharField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Voter Id"))
is_election_staff = forms.BooleanField(initial=False, required=False)
class Meta:
model = CustomUser
fields = ['first_name', 'last_name', 'voter_id', 'date_of_birth', 'sex', 'is_election_staff']
def clean_username(self):
try:
user = User.objects.get(voter_id__iexact=self.cleaned_data['voter_id'])
except User.DoesNotExist:
return self.cleaned_data['voter_id']
raise forms.ValidationError(_("The user with given voter id already exists. Please try another one."))
def clean(self):
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("The two password fields did not match."))
return self.cleaned_data
def save(self, commit=True):
# Save the provided password in hashed format
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.date_of_birth = self.cleaned_data['date_of_birth']
user.sex = self.cleaned_data['sex']
user.voter_id = self.cleaned_data['voter_id']
user.is_election_staff = self.cleaned_data['is_election_staff']
user.username = user.voter_id
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
models.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser)
class Party(models.Model):
name = models.CharField(max_length=200)
num_seats_won = models.IntegerField(default=0)
SEX = (('M', 'MALE'), ('F', 'FEMALE'))
class CustomUser(AbstractBaseUser):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
date_of_birth = models.DateField()
sex = models.CharField(choices=SEX, max_length=10)
is_election_staff = models.BooleanField(default=True)
voter_id = models.CharField(max_length=40, unique=True)
USERNAME_FIELD = 'voter_id'
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
投票/url.py:(这里投票是我的应用程序名)
]
views.py
from .forms import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
import pdb
@csrf_protect
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
print "In register request = "+ str(request.POST)
form.save()
return HttpResponseRedirect('/voting/register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response(
'registration/register.html',
variables,
)
def register_success(request):
print "In success request = "+ str(request)
return render_to_response(
'registration/success.html',
)
def logout_page(request):
logout(request)
return HttpResponseRedirect('/voting/')
@login_required
def home(request):
return render_to_response(
'home.html',
{ 'user': request.user }
)
有人能告诉我我在这里犯的错误吗?提前感谢。您覆盖了用户模型,但在backend.py中进行了更改,该文件用于在用户尝试登录此文件时检查。我认为django正在检查用户模型中的用户名和密码。您的意思是显示
“两个密码字段不匹配。”
错误?当我要登录用户页面时,只要试着打印出self.cleaned_data['password1']
和self.cleaned_data['password2']
No的值,然后输入用户名和密码,就会出现“用户名和密码不匹配”的消息。不,我没有集成任何管理员。对不起,我不知道创建超级用户如何帮助我登录任何用户。您缺少一些东西,可以显示LoginForm代码吗?这里只有注册表格,您是否建议添加backend.py来处理身份验证后端?若要登录,请尝试使用此功能:user\u obj=CustomUser.objects.get(voter\u id=username),除了:return None user=authenticate(username=user\u obj.voter\u id,password=password)如果用户:返回用户返回无
from .forms import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
import pdb
@csrf_protect
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
print "In register request = "+ str(request.POST)
form.save()
return HttpResponseRedirect('/voting/register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response(
'registration/register.html',
variables,
)
def register_success(request):
print "In success request = "+ str(request)
return render_to_response(
'registration/success.html',
)
def logout_page(request):
logout(request)
return HttpResponseRedirect('/voting/')
@login_required
def home(request):
return render_to_response(
'home.html',
{ 'user': request.user }
)