Custom Label in Django Formset

与世无争的帅哥 提交于 2021-02-06 11:41:04

问题


How do I add custom labels to my formset?

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

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

My model is:

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

Now in the template instead of the field label being 'song', how do i set it so that it shows up as 'What song are you going to sing?'?


回答1:


You can use the label argument in your form:

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

If you are using 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

Update:

(@Daniel Roseman's comment)

Or in the model (using verbose_name):

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

or

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


来源:https://stackoverflow.com/questions/5949723/custom-label-in-django-formset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!