Django Formset中的自定义标签

Eva*_*611 6 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>
Run Code Online (Sandbox Code Playgroud)

我的模型是:

class Sing(models.Model):
song = models.CharField(max_length = 50)
band = models.CharField(max_length = 50)
Run Code Online (Sandbox Code Playgroud)

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

man*_*nji 18

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

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

如果您正在使用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
Run Code Online (Sandbox Code Playgroud)

更新:

(@Daniel Roseman的评论)

或者在模型中(使用verbose_name):

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

要么

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

  • `label`应该是`verbose_name`,或者只使用第一个位置参数. (2认同)