I’m using Django 4.2.9 and need a form add an additional class to an input field, in case the validiation failed.
I can already add classes for every case, but I do not know how to do it for the error-case.
class ItemForm(forms.models.ModelForm):
class Meta:
model = Item
fields = ("text", )
widgets = {
"text": forms.widgets.TextInput(
attrs={
"placeholder": "Enter a to-do item",
"class": "form-control form-control-lg",
}
),
}
error_messages = {"text": {"required": EMPTY_ITEM_ERROR}}
def save(self, for_list):
self.instance.list = for_list
return super().save()
I’d like to have class="form-control form-control-lg is-invalid"
for the text-input.
<form method="POST" action="/lists/8/">
<input type="text" name="text" value="Buy wellies" placeholder="Enter a to-do item" class="form-control form-control-lg" required id="id_text">
<input type="hidden" name="csrfmiddlewaretoken" value="vcojkMtz3GeonURczjMwIsbsDPQUbeKgrXrPIxZY4jIJSfuUKKGVgaj7wLQBatsd">
<div class="invalid-feedback"><ul class="errorlist"><li>You've already got this in your list</li></ul></div>
</form>
2
Answers
I would probably in your case when validation fails over ride the init in the following way:
class ItemForm(forms.models.ModelForm):
This way we add "is-invalid" class on the text input when validation fails. So basically and hopefully this code will check for any erros in the form text fields. If there is we will be "is-invalid"
I think a better approach (I like everything in parts) is to put the error classes in separate methods so depending what else your project does you might reuse them going forward.
Good luck 🙂
This kind of job must be done in _post_clean method not init. Cause you initiate the form. First Time without args ItemForm(), and after post request ItemForm(request.POST). When you use in your view :
With is valid your form will run full_clean. After fields cleaning will be run _post_clean that you can override :
For more détails of validation :
https://docs.djangoproject.com/en/5.0/ref/forms/validation/
Hope it will help you.