Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

python - How to markup form fields with <div class='field_type'> in 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.

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
class MyForm(forms.Form):
    myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'}))

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

render normally with {{ form }}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...