2👍
✅
You shouldn’t be trying to prevent submission when the form is invalid. What you should be doing is accepting the submission, checking the errors, then returning the errors and the filled-in form to the template.
But you are doing three things that prevent that: you are always re-instantiating the form when it is invalid, you always redirect, and you don’t show errors or previous values in the template.
So you should do this:
def register(request):
form = UserRegistrationForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
user = User.objects.create_user(username=username, password=password, email=email)
user.save()
return redirect('/')
return render('mytemplate.html', {"form": form})
and in the template:
<div class="registerBox">
{{ form.non_field_errors }}
<p>{{ form.username.label_tag }} {{ form.username }} {{ form.username.errors }}</p>
<p>{{ form.email.label_tag }} {{ form.email }} {{ form.email.errors }}</p>
<p><label for="id_password"></label> <input type="password" name="password" id="id_password" placeholder="password"/></p>
<p><label for="id_confirm_password"></label> <input type="password" name="confirm_password" id="id_confirm_password" placeholder="confirm password"/></p>
<input type="submit" value="register" />
</div>
Source:stackexchange.com