首页 > 解决方案 > 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 do anything and just focuses the field with the error.

Forms.py

class CreateUserForm(UserCreationForm):
  username = forms.CharField(required=True, max_length=30) 
  email = forms.EmailField(required=True)
  first_name = forms.CharField(required=True, max_length=50)
  last_name = forms.CharField(required=True, max_length=50)
  
  class Meta:
    model = User
    fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2',]
    

If anyone needs any more details, feel free to let me know. Thank you to everyone who helps!

标签: pythonhtmlcssdjango

解决方案


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


推荐阅读