How to Add a Placeholder to a Django Form Field


In this article, we show how to add a placeholder to a Django form field.

A placeholder is text that goes into a form field that can be used to tell the user information. This text disappears when a user clicks in the field and begins typing. The text of a placeholder is only there temporarily to tell the user some type of information.

Implementing this in an HTML form is as simple as putting the text, placeholder="some text", 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. File

In the file, in order to add a placeholder to a field, we use put a dictionary in the attrs attribute of the form field.

This is shown below.

So this is our file.

We have 3 fields, firstname, email, and phonenumber, all of which have placeholders.

In order to add a placeholder 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={'placeholder':'Value of placeholder'}

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 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 file.

And this is how to add a placeholder to a Django form field.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...