我有一个允许用户创建用户帐户的表单。问题是,每当用户提交已经通过系统获取的用户名时。表单不会引发错误,但在缺少字段时会引发错误。有人可以帮助我吗
def Registration(request):
form = UserRegistration()
if request.method =='POST':
form = UserRegistration(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
email=form.cleaned_data['email'],
password=form.cleaned_data['password']
)
user.is_active = True
user.save()
return render(request,'choose.html',{'form':form})
return render(request, 'register.html', {'form': form},)
我的forms.py
class UserRegistration(forms.Form):
username = forms.CharField()
email = forms.EmailField(error_messages={'required':'Error Missing Field , Please Fill this Field'})
password = forms.CharField(
widget=forms.PasswordInput(render_value=False)
)
def clean(self):
cleaned_data = super(UserRegistration, self).clean()
username = cleaned_data.get("username")
password = cleaned_data.get("password")
user = User.objects.filter(username=username)
if user :
raise forms.ValidationError(
"That user is already taken , please select another ")
return cleaned_data
我的模板
<form method ="POST">
{% csrf_token %}
<span id="error">{{form.username.errors}}</span>
<span id="error2">{{form.email.errors}}</span>
<span id="error3">{{form.password.errors}}</span>
{{form.username}}
{{form.email}}
{{form.password}}
<input type = "submit" value= "save" id="box2"/>
</form>
答案 0 :(得分:3)
您应该使用exists
[0]方法:
user = User.objects.filter(username=username)
if user.exists():
raise forms.ValidationError("That user is already taken")
编辑:
尝试使用clean_username
方法:
class UserRegistration(forms.Form):
....
def clean_username(self):
username = self.cleaned_data['username']
if User.objects.filter(username=username).exists():
raise forms.ValidationError("That user is already taken")
return username
您可以添加测试以确保其有效:
from django.test import TestCase
class TestUniqueUsername(TestCase):
def test_unique_username(self):
User.objects.create(username='test', password='test', email='test@django.com')
form = UserCreationForm(data={'username': 'test'})
self.assertFalse(form.is_valid())
[0] https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.exists
答案 1 :(得分:0)
试试此代码
class UserRegistration(forms.Form):
username = forms.CharField()
email = forms.EmailField(error_messages={'required':'Error Missing Field , Please Fill this Field'})
password = forms.CharField(
widget=forms.PasswordInput(render_value=False)
)
def clean_username(self):
cleaned_data = self.cleaned_data
username = cleaned_data.get("username")
user = User.objects.filter(username=username)
if user.count() > 0:
raise forms.ValidationError("That user is already taken , please select another ")
return username
这样就可以了。