Dynamically set the placeholder for Django Form fields

Consider, we have an employee form and we want to have placeholders for form inputs so after we rendered our form we can get amazing input labels. How can we achieve this?

Say our employee form has model with fields like employee_name, date_of_joining, mobile_number and email. To edit the widget attributes we can use following code template:

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

here, field_name is the name of our form field, attribute_name is the property of that field (in this case it will be ‘placeholder’) and field_value is the value which we are going to assign. To make the changes we need to add placeholder attribute in our form class constructor.

There are two ways with which we can assign the placeholder value.

  1. Using Static value:

2. Dynamically set the placeholder value:

This is generally helpful when we have lots of field which we need to display in the form and with this our code is more in readable format. If you render the form you will see the placeholder for inputs.

Now that you have a placeholder for your fields and if you don’t want to display label for fields then simply add below code at the bottom of for loop.

self.fields[field_name].label = ''

Hope this was helpful 😊

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store