如何在Django </div>中使用<div class =“field_type”>标记表单字段

时间:2009-09-21 08:53:05

标签: python django django-forms django-templates django-models

我无法找到识别django模板中字段类型的方法。我的解决方案是创建一个简单的过滤器来访问字段和窗口小部件类名。我已经包含了下面的代码,以防它对其他人有用。

有更好的方法吗?

## 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 个答案:

答案 0 :(得分:22)

class MyForm(forms.Form):
    myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'}))

或使用ModelForm

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),
        }

或者,当您不想重新定义小部件时

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'})

使用{{form}}

正常渲染