Django Formset中的自定义标签

时间:2011-05-10 12:04:21

标签: django django-templates django-forms formset

如何向自己的formset添加自定义标签?

<form method="post" action="">

    {{ formset.management_form }}
    {% for form in formset %}
        {% for field in form %}
            {{ field.label_tag }}: {{ field }}
        {% endfor %}
    {% endfor %}
</form>

我的模特是:

class Sing(models.Model):
song = models.CharField(max_length = 50)
band = models.CharField(max_length = 50)

现在在模板中而不是字段标签为'song',如何设置它以使其显示为'What song are you going to sing?'

1 个答案:

答案 0 :(得分:17)

您可以在表单中使用label参数:

class MySingForm(forms.Form):
    song = forms.CharField(label='What song are you going to sing?')
    ...

如果您使用ModelForms

class MySingForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MySingForm, self).__init__(*args, **kwargs)
        self.fields['song'].label = 'What song are you going to sing?'

    class Meta:
        model = Sing

更新

@Daniel Roseman的评论

或在模型中(使用verbose_name):

class Sing(models.Model):
    song = models.CharField(verbose_name='What song are you going to sing?',
                            max_length=50)
    ...

class Sing(models.Model):
    song = models.CharField('What song are you going to sing?', max_length=50)
    ...