[Django]-How to render form field with information that it is required

37πŸ‘

βœ…

As of Django 1.2, if your form has an attribute named required_css_class, it will be added to BoundField.css_classes for required fields. You can then use CSS to style the required parts of the form as desired. A typical use case:

# views.py
class MyForm(django.forms.Form):
    required_css_class = 'required'
    …

…

/* CSS */
th.required { font-weight: bold; }

…

<!-- HTML -->
<tr>
  <th class="{{form.name.css_classes}}">{{form.name.label_tag}}</th>
  <td>{{form.name.errors}}{{form.name}}</td>
</tr>

If you use Form.as_table(), Form.as_ul, and Form.as_p, they do this automatically, adding the class to <tr>, <li>, and <p>, respectively.

πŸ‘€Vebjorn Ljosa

13πŸ‘

You also can use a field.field.required property:

{% for field in form %}
  {{field.label}} {% if field.field.required %} * {% endif %}
  {{field}}
  {{field.errors}}
{% endfor %}

1πŸ‘

The best way for such purposes I have found is to render form’s output via an html template. How to do this is described here. By luck, the example puts an asterisk after required fields just like you want.

πŸ‘€shanyu

1πŸ‘

I use a template tag to render form fields with their labels and errors, plus an asterisk and a CSS class for required fields. There are various snippets available to do it on www.djangosnippets.org

0πŸ‘

Personny I tried something like this, i.e. overriding the default template tag (this adds a red asterisk in all the admin interface for required not-readonly fields. Then i also defined a 2nd tag for my views that mix inline and block labels. See the code below (copy/paste of Django source code with some modifications):

In settings.py :

from django.forms.util import flatatt
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
import django.forms.forms as django_forms
def custom_label_tag(self, contents=None, attrs=None):
        """
        Wraps the given contents in a <label>, if the field has an ID attribute.
        Does not HTML-escape the contents. If contents aren't given, uses the
        field's HTML-escaped label.

        If attrs are given, they're used as HTML attributes on the <label> tag.
        """
        contents = contents or conditional_escape(self.label)
        widget = self.field.widget
        id_ = widget.attrs.get('id') or self.auto_id
        if id_:
            attrs = attrs and flatatt(attrs) or ''
            if self.field.required:
                label = unicode(contents)
                label_suffix = ""
                if label[-1] == ":":
                    label = label[:-1]
                    label_suffix += ":"
                contents = u'<label for="%s"%s>%s<span style="color:red;">*</span>%s</label>' % (widget.id_for_label(id_), attrs, label, label_suffix)
            else:
                contents = u'<label for="%s"%s>%s</label>' % (widget.id_for_label(id_), attrs, unicode(contents))
        return mark_safe(contents)

def custom_inline_label_tag(self, contents=None, attrs=None):
    if attrs:
        if "class" in attrs.keys():
            attrs["class"] += " inline"
        else:
            attrs["class"] = "inline"
    else:
        attrs = {"class": "inline"}
    return self.label_tag(contents, attrs)
django_forms.BoundField.label_tag = custom_label_tag # override django method
django_forms.BoundField.inline_label_tag = custom_inline_label_tag

In my templates

<p>{{ form.fieldname.errors}}{{ form.fieldname.inline_label_tag }}{{form.fieldname}}</p>
OR
<p>{{ form.fieldname.errors}}{{ form.fieldname.label_tag }}{{form.fieldname}}</p>
πŸ‘€Ricola3D

Leave a comment