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 %}
        {% forerror in field.errors %}
            {{ error|escape }}
        {% endfor %}
    {% endfor %}
    {% forerror 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"