Muhammad Alkarouri Muhammad Alkarouri - 1 year ago 58
Python Question

How to add required attribute to a Django form field

I would like to have a Django form field render as:

<input type="text" name="username" required>

but when I try
username.widget.attrs['required'] = ''
I get something like:

<input type="text" name="username" required="">

Is there a way in which the standalone HTML5 attributes like
can be shown in the resulting HTML form?

I am using Django 1.6 on Python 2.6, for what it's worth.

Answer Source

You need to define the required attribute in a valid format.

username.widget.attrs['required'] = 'required'

Take a look here for more details: