[Django]-Django: How to update a class attribute of an invalid form field to display error messages in Bootstrap 5?

3👍

I don’t know correct way but this way I’ve done my job

if form.is_valid():
    form.save()
    return redirect("success")
else:
    for field in form.errors:
        form[field].field.widget.attrs['class'] += ' is-invalid'

this will add is-invalid class to all invalid fields
Note: don’t forget to add space ' is-invalid'

0👍

Add a conditional css class to all the fields that have errors like this

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for field in self.errors:
            attrs = self[field].field.widget.attrs
            attrs.setdefault("class", "")
            attrs["class"] += " is-invalid"

Leave a comment