Adding css class to field on validation error in django Adding css class to field on validation error in django python python

Adding css class to field on validation error in django


To answer the original question.

You can add the desired class to the field in the view to where you are submitting your form and doing your form.is_valid() check. Not the prettiest but it will work.

def submit_form(request):    if request.method = 'POST':        if. form.is_valid():            # Do something with clean form data            pass        else:            # Append css class to every field that contains errors.            for field in form.errors:                form[field].field.widget.attrs['class'] += ' my-css-class'    return render(request, submit_form.html, {        'form': form    })


Expanding upon errx's answer.

Add the CSS

.error input, .error select {    border: 2px red solid;}

to specifically highlight the field