如何使用< div class ='field_type'>来标记表单字段在Django [英] How to markup form fields with <div class='field_type'> in Django

查看:180
本文介绍了如何使用< div class ='field_type'>来标记表单字段在Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有更好的方法吗?

## 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>


推荐答案

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

或者使用ModelForm

or, with a ModelForm

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

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

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

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}}渲染

render normally with {{ form }}

这篇关于如何使用&lt; div class ='field_type'&gt;来标记表单字段在Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆