Override Field Widget Attributes in a Django Form or How To Add Placeholder Attribute to Django Form Input

18 Jan ยท by Tim Kamanin ยท 1 min read

Let's say we have a contact form and we want to add placeholders to this form inputs so our rendered form has these cool input labels. How do we do that?

My form is a child of ContactForm class provided by the django_contact_form module. The module defines default fields for that form: name, email, and message. We need to add a placeholder attribute in our form class constructor.

In order to edit field widget attributes, we need to use the following code template

self.fields['field_name'].widget.attrs['attribute_name'] = 'attribute_value'

where field_name is a name of our field (email, for example), attribute_name is a name of our attribute (in our case it's a placeholder) and attribute_value is a value we want the attribute to have (in our example it's a label).

Here's the result:

from contact_form.forms import ContactForm

# My form is a child of ContactForm class provided by django_contact_form module
class MyContactForm(ContactForm):

    def __init__(self, data=None, files=None, request=None, recipient_list=None, *args, **kwargs):
        super().__init__(data=data, files=files, request=request, recipient_list=recipient_list,
            *args, **kwargs)
        self.fields['name'].widget.attrs['placeholder'] = 'name'
        self.fields['email'].widget.attrs['placeholder'] = 'e-mail'
        self.fields['body'].widget.attrs['placeholder'] = 'message'

Now you can render the form in a template and you'll see that inputs now have placeholders.

Hope this one was helpful. Till next time.

Want to get more ๐Ÿ”ฅ tips like this one?

Subscribe to get notified about new dev tutorials