Muhammad Alkarouri Muhammad Alkarouri - 5 months ago 9
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
required
can be shown in the resulting HTML form?

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

Answer

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

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

Take a look here for more details: http://stackoverflow.com/a/3012975/1566605