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


2 Comments on “Display asterisks for required fields in template”

  1. 1 Liza said at 4:00 pm on January 12th, 2010:

    AWWWW SHIT Im on a boat!

  2. 2 Arif Harbott said at 9:49 pm on January 12th, 2010:

    That is a good post thanks for that. I am surprised that there is not a better method for doing that, I see that someone has submitted a ticket to the Django developers for that.

    I am happy you have highlighted the locals() function, it is a good way to assign variable to the template automatically (in a small way it is like the extract() function in PHP).

    Keep it going and I look forward to more posts from you in the future!


Leave a Reply