[Fixed]-Django form.errors not showing up in template

18👍

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 not form.error

{% if form.error %}  {% if form.errors %}

Leave a comment