Search code examples
djangodjango-formsbootstrap-5

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


When I use server-side validation in Bootstrap 5, I need to add an .is-invalid class to the input form field with an error to display it in div with class="invalid-feedback". To update a class attribute of a form field in Django I can do this, as stated in the docs:

class CommentForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({'class': 'special'})
        self.fields['comment'].widget.attrs.update(size='40')

But I cannot figure out how to add .is-invalid to the form field when the form is returned invalid. I have found this in the docs, but it doesn't work.


Solution

  • 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'