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

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 (https://github.com/ubernostrum/django-contact-form). 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

1
  1. 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  1. from contact_form.forms import ContactForm
  2. # My form is a child of ContactForm class provided by django_contact_form module
  3. class MyContactForm(ContactForm):
  4. def __init__(self, data=None, files=None, request=None,
  5. recipient_list=None, *args, **kwargs):
  6. super().__init__(data=data, files=files, request=request, recipient_list=recipient_list,
  7. *args, **kwargs)
  8. self.fields['name'].widget.attrs['placeholder'] = 'name'
  9. self.fields['email'].widget.attrs['placeholder'] = 'e-mail'
  10. 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.