I have refrenced this stackoverflow page and tried to display my forms error on the html template. I did:
{% if form.error %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
as said in the stackoverflow question I also tried simply doing:
{% if form.error %}
This should pop up if there is an error
{% endif %}
Nothing comes up regardless: Heres my view.py code:
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password2')
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect('/')
else:
print(form.errors)
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
I am able to get the form errors onto the django console but it refuses to show up on the template.
Printing form.errors
prints to the console: <li>password2<ul class="errorlist"><li>The two password fields didn't match.</li></ul></li></ul>
forms.errors
fired up, but at the end, you declare a new form form = UserCreationForm()
just before you render your view.
After checking whether the form
is valid or not, all your validation errors are inside form
instance, remember processes run as sequence, at the end, you destroy the variable form
with form = UserCreationForm()
so no validation errors anymore.
What you can do is add this new form form = UserCreationForm()
to else statement when your request method is GET
to keep having an empty form. By adding the else
statement you avoid the new assignment of the form; after the validation process, it will jump to render(request,....)
with the form
instance containing all validation errors
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password2')
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect('/')
else:
print(form.errors)
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
Note, the correct call for form errors in templates is
form.errors
with s notform.error
{% if form.error %} {% if form.errors %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With