Display asterisks for required fields in template

Posted: January 11th, 2010 | Author: Davo | Filed under: Django | Tags: , , , , | 2 Comments »

If you want to display simple asterisks (*) for required fields in Django then the following code is for you.
The trick is to access the field properties inside the template and make a conditional statement.
Here is a simple example of view and template:

# this is inside your views.py
def do_something(request):
      """Display simple form"""
      form = MyForm() # this will be used in the template.
      return render_to_response('template.html', locals())

# this is inside your template.html
{% for field in form %} {{ field }} {% if field.field.required %}(*){% endif %} {% endfor %}

The locals() function is a built in python function