views:

249

answers:

1

I wasn't able to find a way to identify the type of a field in a django template. My solution was to create a simple filter to access the field and widget class names. I've included the code below in case it's helpful for someone else.

Is there a better approach?

## agency/tagutils/templatetags/fieldtags.py
###############################################################
from django import template

register = template.Library()

@register.filter(name='field_type')
def field_type(value):
    return value.field.__class__.__name__

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


## client/project/settings.py
###############################################################

INSTALLED_APPS = (
 # ...
 'agency.tagutils',
)


## client/project/templates/project/field_snippet.html
###############################################################

{% load fieldtags %}

<div class="field {{ field|field_type }} {{ field|widget_type }} {{ field.name }}">
     {{ field.errors }}
    <div class="form_label">
        {{ field.label_tag }}
    </div>
    <div class="form_field">
    {{ field }}
    </div>
</div>


## sample output html
###############################################################
<div class="field CharField TextInput family_name">    
    <div class="form_label">
        <label for="id_family_name">Family name</label>
    </div>
    <div class="form_field">
    <input id="id_family_name" type="text" name="family_name" maxlength="64" />
    </div>
</div>
+1  A: 
class MyForm(forms.Form):
    myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'}))

or, when you don't want to redefine the field

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class' : 'myfieldclass'})

render normally with {{ form }}

shadfc