6

如何将自定义标签添加到我的表单集?

<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?'

4

1 回答 1

20

您可以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

更新:

@丹尼尔罗斯曼的评论

或在模型中(使用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)
    ...
于 2011-05-10T12:16:54.363 回答