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 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
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 placeholder) and attribute_value
is a value we want attribute to have (in our example it's a label).
Here’s the result:
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.
This post was originally posted on my blog: http://timonweb.com/posts/override-field-widget-attributes-in-a-django-form-or-how-to-add-placeholder-attribute-to-django-form-input/