Test a django ModelForm field to determine if it is “required”

by Glyn Mooney

In Django when creating form templates it’s good practice in the field’s of accessibility and usability to mark a field as “required”. Django provides us with numerous methods to render forms into custom templates but most of the time it is quite nice to be able to just iterate over all of the fields in the form object and render them out in turn. In cases like this it might be required denote some form fields as “required”. Below I will demonstrate how you would typically render a form in a loop and detect if the current form element is required:

{% extends 'base.html' %}
{% load i18n %}

{% block content %}
  <h2>{% trans "Contact Us" %}</h2>
  <form id="contact" method="post">
    <fieldset>
      <legend>{% trans "Contact Form" %}</legend>
      {% for field in form %}
        <div class="form-item">
          {% if field.errors %}
            <div class="error">{{ field.errors|striptags }}</div>
          {% endif %}
          {% if not field.is_hidden %}<label for="{{ field.auto_id }}">{% trans field.label %} {% if field.field.required %}<span class="required">({% trans "Required" %})</span>{% endif %}{% endif %}</label>
          {{ field }}
        </div>
      {% endfor %}
      <div class="buttons"><input id="submit" class="form-submit" name="submit" type="submit" value="{% trans 'Submit' %}" tabindex="100" /></div>
    </fieldset>
  </form>
{% endblock content %}

The important part of the snippet above is the “{% if field.field.required %}”. The required attribute of the current element object, in this case “field”, resides in “field.required”. So just to firm this in your mind it in “{object}.field.required” or “{form_object}.{object}.field.required”.

Hope this helps.