Skip to content Skip to sidebar Skip to footer

Displaying Validation Error Instead Of Default Text Errors In Django UserCreationForm

I have a very simple registration form on my website. My form works, but if a username already exists or my 2 password fields don't match, after I submit the form, Django does not

Solution 1:

If I understand you right, you can show errors from the form in your template. Something like this:

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            {{ error|escape }}
        {% endfor %}
    {% endfor %}
    {% for error in form.non_field_errors %}
        {{ error|escape }}
    {% endfor %}
{% endif %}

Detailed documentation: https://docs.djangoproject.com/en/3.2/ref/forms/api/#django.forms.Form.errors


Solution 2:

Ended up figuring it out. Basically, you need to make a function inside of your forms.py file and query the default Django SQL database in order to see if the username already exists. For anyone having the same problem as me, my code is down below.


def clean(self):
          cleaned_data=super().clean()
          if User.objects.filter(username=cleaned_data["username"]).exists():
            raise ValidationError("The username is taken, please try another one")

Post a Comment for "Displaying Validation Error Instead Of Default Text Errors In Django UserCreationForm"