Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to check if field widget is checkbox in the template?

I've created a custom template for rendering form fields:

<tr class="{{field.field.widget.attrs.class}}">
    <th class="label">
        <label for="{{field.auto_id}}">
            {{field.label}}
            {% if not field.field.required %}<span class="optional">(optional)</span>{% endif %}
        </label>
    </th>
    <td class="field">
        {{field}}
        {% if field.errors %}<label class="error" for="{{field.auto_id}}">{{field.errors.0}}</label>{% endif %}
        {% if field.help_text %}<small class="help-text">{{field.help_text}}</small>{% endif %}
    </td>
</tr>

But I want to check if the widget is a checkbox, and if so, render it differently. How can I do that in the template?

like image 465
mpen Avatar asked Oct 13 '10 18:10

mpen


3 Answers

{{ field.field.widget.input_type }} will get you this info for a lot of widgets, but not all. I'm not sure if it'll work for the default checkbox widget or not. Worth a shot.

like image 37
Jeff Croft Avatar answered Oct 31 '22 08:10

Jeff Croft


Use a custom template filter!

In yourapp/templatetags/my_custom_tags.py:

from django import template
from django.forms import CheckboxInput

register = template.Library()

@register.filter(name='is_checkbox')
def is_checkbox(field):
  return field.field.widget.__class__.__name__ == CheckboxInput().__class__.__name__

In your template:

{% load my_custom_tags %}
 
{% if field|is_checkbox %}
  do something
{% endif %}

Side note on implementation: when I don't instantiate a CheckboxInput, the class name is MediaDefiningClass.

>>> form django.forms import CheckboxInput
KeyboardInterrupt
>>> CheckboxInput.__class__.__name__
'MediaDefiningClass'
like image 100
davidtingsu Avatar answered Oct 31 '22 07:10

davidtingsu


It is kind of late to answer, but I implemented something similar to what is done in Django's admin.

First, I added a new attribute is_checkbox to the Field class:

# forms.py
from django import forms
from django.forms.fields import Field
setattr(Field, 'is_checkbox', lambda self: isinstance(self.widget, forms.CheckboxInput ))

Then, I can easily detect a CheckboxInput widget in the template. Here is an example to render checkboxes to the left and other widgets to the right:

{% if field.field.is_checkbox %}
    {{ field }} {{ field.label_tag }}
{% else %}
    {{ field.label }} {{ field }}
{% endif %}
like image 33
Alexandre Avatar answered Oct 31 '22 09:10

Alexandre