How to Add a Class or id Attribute to a Django Form Field



Python


In this article, we show how to add a class or id attribute to a Django form field.

With a class or id attribute, we can add styling to a form field with CSS. We also can give the form field functionality with Javascript.

So knowing how to do this is very important.

Implementing this in an HTML form is as simple as putting the text, class="some_class", or id= "some_id", into the form field.

Implementing this in a Django form is still relatively simple, even though it requires a little more code.

So let's see how to implement this into a form in Django.


forms.py File

In the forms.py file, in order to add a class or id attribute to a field, we use put a dictionary in the attrs attribute of the form field.

This is shown below.



So this is our forms.py file.

We have 2 fields, firstname and email, both of which have class and id attributes.

In order to add a class or id attribute to a form in Django, we have to place a widget=form.TextInput (or widget= form.EmailInput, if email input) within the form field (because it's a text field). Inside of this widget, we then have to put, attrs={'class':'some_class'}. If we want an id attribute, then we place an id attribute within the dictionary of the attrs dictionary. attrs={'id':'some_id'}.

To add a placeholder to a form field within a Django ModelForm, we do the same but we don't have to define things already in the models.py file, such as the max_length.

This is shown in the code below.



It's the same as the form before, but now we don't have to add the max_length attribute, because it would already be defined in the models.py file.

Now within the template file that is render containing this form, we can add CSS styling or Javascript functionality to the form.

And this is how to add a class or id attribute to a Django form field.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...