代码运行良好但是在尝试将新用户添加到站点时,它仅以超级用户身份登录。
模型
class RegistrationForm(forms.Form):
username = forms.CharField(label = 'Username', max_length = 30)
first_name = forms.CharField(label = 'First name', max_length = 30,widget=forms.TextInput(attrs={'class' : 'Name'}))
last_name = forms.CharField(label = 'Last name', max_length = 30,widget=forms.TextInput(attrs={'class' : 'Name'}))
email1 = forms.EmailField(label = 'email', required = True,widget=forms.TextInput(attrs={'class' : 'email'}))
email2 = forms.EmailField(label = 'Re-enter email',widget=forms.TextInput(attrs={'class' : 'email'}))
password1 = forms.CharField(label= "Password", widget = forms.PasswordInput(attrs={'class' : 'password1'}))
birthday = forms.DateField(label = 'Birthday',widget=forms.TextInput(attrs={'class' : 'birthday'}))
class Meta:
model = User
fields = ('username', 'email', 'password1','password2')
def save(self, commit = True):
user = super(RegistrationForm, self).save(commit = False)
user.email1 = self.cleaned_data['email1']
user.email2 = self.cleaned_data['email2']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.birthday = self.cleaned_data['birthday']
if commit:
user.save()
return user
def clean_username(self):
email1 = self.cleaned_data['email1']
if not re.search(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email1):
raise forms.ValidationError('Use a real email address eg. something@example.com.')
try:
user.objects.get(email1 = email1)
except ObjectDoesNotExist:
return username
raise forms.ValidationError('email is already in use.')
def clean_username(self):
username = self.clean_data['username']
if not re.search(r'^\w+$', username):
raise forms.ValidationError('Username can only contain alphanumeric characters and the underscore.')
try:
user.objects.get(username = username)
except ObjectDoesNotExist:
return username
raise forms.ValidationError('Username is already taken.')
浏览
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
user = User.objects.create_user(
username = form.clean_data['username'],
password = form.clean_data['password1'],
email = form.clean_data['email']
)
return HttpResponseRedirect('/register/success/')
else:
args = {}
args.update(csrf(request))
args['form'] = RegistrationForm()
print(args)
return render(request, 'registration/register.html', args)