[Answered ]-Django validate fileds on form and return on template

1👍

There is a syntax error in your clean method.

    def clean(self):
        cleaned_data = super().clean()
        # self.password = cleaned_data('password')
        self.password = cleaned_data.get('password')
        # self.repassword = cleaned_data('repassword')
        self.repassword = cleaned_data.get('repassword')
        if self.password != self.repassword:
            raise ValidationError('Password dont match')

Also, keep in mind that there are two ways to validate fields in the form:

  1. clean method – should be used when there are two or more interdependent fields that require validation
  2. clean_<field_name> method – clean method for a single field

This is important because the errors are stored differently for these two methods. The clean_<field_name> method stores the errors in the form.errors dict which you are correctly rendering in your HTML. However, clean method stores the errors in form.non_field_errors. To render these I suggest adding this line above your form code:

<form action="{% url 'create_users:add_user' %}" method="POST">
    {% csrf_token %}
    
    {# Renders errors reported in clean method #}
    {{ form.non_field_errors }}

    {% for field in form %}
        <div class="mb-3">
            {{ field }}
        </div>
        {% for error in field.errors %}
            <div class="alert alert-danger">{{error}}</div>
        {% endfor %}
    {% endfor %}
    ...     
</form>

One last thing

I found some issues in your view code. I will add below a commented version of your code:

def index(request):
    form = UserForm()
    if request.method == 'POST':
        form = UserForm(request.POST or None)
        if form.is_valid():
            firstname= form.cleaned_data.get("first_name")
            lastname= form.cleaned_data.get("last_name")
            password = form.cleaned_data.get('password')
            re_password = form.cleaned_data.get('repassword')

            # DON'T override the form here. If the form is invalid
            # you want to re-render that exact form instance because
            # it will contain the errors
            # form = UserForm()
            context = {'form': form}

            # If the form is valid, you want to redirect to the success page
            # See this antipattern: https://www.django-antipatterns.com/antipattern/rendering-content-after-a-successful-post-request.html
            return render(request, 'create_users/index.html', context)
    return render(request, 'create_users/index.html', {'form': form}

Leave a comment