在创建我的注册以发布和通过时遇到问题。它正在抛出我的错误消息已经采用了用户名并且电子邮件已经被采用,当两者都没有时,即使我输入了全新的信息集。有人认为他们可以帮忙解决吗?
Forms.py:
class SignupForm(forms.ModelForm):
email=forms.EmailField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Email', 'required':True}))
username=forms.CharField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Username','required':True}))
password=forms.CharField(max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Password','required':True}))
password2=forms.CharField(max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Re-Enter Password','required':True}))
class Meta:
""" To Specify the fields from User model from django, and to prevent abstraction"""
model = User
fields = ['email', 'username', 'password', 'password2']
def clean_username(self):
users = self.cleaned_data["username"]
if not users:
return self.cleaned_data["username"]
raise forms.ValidationError("This username already exist")
def clean_email(self):
emails = self.cleaned_data["email"]
if not emails:
return self.cleaned_data["email"]
raise forms.ValidationError("Email is already registered")
def clean_password2(self):
password = self.cleaned_data.get("password")
password2 = self.cleaned_data.get("password2")
if not password2:
raise forms.ValidationError("You must confirm your password")
if password != password2:
raise forms.ValidationError("The password does not match ")
return password2
views.py:
def signup(request):
template_var={}
form=SignupForm(request.POST or None)
if request.POST and form.is_valid():
user = form.login(request)
if user:
login(request,user)
return HttpResponseRedirect("register")
template_var["form"]=form
return render_to_response("registration/signup.html",template_var,context_instance=RequestContext(request))
答案 0 :(得分:1)
在clean_username(self)
中,为什么只返回self.cleaned_data["username"]
为空(not users == True
}的情况?而且您实际上并未检查重复的用户名。
该功能应如下所示:
def clean_username(self):
username = self.cleaned_data["username"]
if not username:
raise forms.ValidationError("You must enter a username.")
if User.objects.filter(username=username).count() > 0:
raise forms.ValidationError("This username already exists.")
return username
您的电子邮件检查具有相同的错误。