1👍
✅
You can add clean_
method to the form class to validate the username field:
def clean_username(self):
username = self.cleaned_data.get('username')
if username:
user = User.objects.filter(username=username)
if user.exists():
raise forms.ValidationError(
_('That username exists in our system. Please try another.'),
code='unique_username'
)
return username
Afterwards you should rewrite your view function to pass the form object to the registration template:
def register_user(request):
args = {}
args.update(csrf(request))
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
args['form'] = form
return render_to_response('register.html', args)
args['form'] = MyRegistrationForm()
print args
return render_to_response('register.html', args)
I’m going to recommend that you find out how to display the error messages in the template by yourself.
These pages from Django’s documentation should provide more insight:
Source:stackexchange.com