Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django input element error css class

I'd like to know how can I add .error class to input elements (to registration app) when the form validation fails.

like image 303
Eeyore Avatar asked Feb 04 '10 01:02

Eeyore


People also ask

Can I add custom CSS classes to Django form fields?

However, Django itself does not allow one-off customizations of form-generated HTML. In this post I will discuss a method for customizing the HTML generated by Django form fields, with the specific goal of adding custom CSS classes to Django form fields. Here’s a Django form definition: Here’s the form used in a template:

What are some examples of input elements in Django?

As an example, the login form for the Django admin contains several <input> elements: one of type="text" for the username, one of type="password" for the password, and one of type="submit" for the “Log in” button. It also contains some hidden text fields that the user doesn’t see, which Django uses to determine what to do next.

What is a form in Django?

In the context of a web application, ‘form’ might refer to that HTML <form>, or to the Django Form that produces it, or to the structured data returned when it is submitted, or to the end-to-end working collection of these parts. At the heart of this system of components is Django’s Form class.

How do you handle errors for hidden fields in Django?

For example, because hidden fields don’t display anything, putting error messages “next to” the field could cause confusion for your users – so errors for those fields should be handled differently. Django provides two methods on a form that allow you to loop over the hidden and visible fields independently: hidden_fields () and visible_fields ().


1 Answers

If you want to place your error CSS class to form input widgets (not their containers), you can derive your form class from the following one:

class StyledErrorForm(forms.Form):
     def is_valid(self):
         result = super().is_valid()
         # loop on *all* fields if key '__all__' found else only on errors:
         for x in (self.fields if '__all__' in self.errors else self.errors):
             attrs = self.fields[x].widget.attrs
             attrs.update({'class': attrs.get('class', '') + ' is-invalid'})
         return result
like image 133
Luca Avatar answered Oct 04 '22 20:10

Luca