Django username already taken error -
i have form allows user create user account.the problem , whenever user submit username been taken through system . form doesn't raise error raise error when field missing. can kindly me
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},)
my forms.py
class userregistration(forms.form): username = forms.charfield() email = forms.emailfield(error_messages={'required':'error missing field , please fill 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 taken , please select ") return cleaned_data
my template
<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>
you should use exists
[0] method:
user = user.objects.filter(username=username) if user.exists(): raise forms.validationerror("that user taken")
edit:
try using clean_username
method:
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 taken") return username
you add test make sure works:
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
Comments
Post a Comment