Custom Label in Django Formset
Asked Answered
P

1

9

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

Palila answered 10/5, 2011 at 12:4 Comment(2)
What do you mean by "custom labels"? How should they look? Where should they be displayed? What's the point of that template extract?Poriferous
sorrt for being unclear. view edits?Palila
H
23

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)
    ...
Huh answered 10/5, 2011 at 12:16 Comment(5)
i get TypeError: __init__() got an unexpected keyword argument 'label'Palila
label should be verbose_name, or just use the first positional argument.Poriferous
Answer updated. label argument is used only with Form fields not Model fields (my mistake). Can you post your form definition so that I can give you a 100% working solution?Huh
I was using ModelForm class SingForm(ModelForm): Class Meta: model = SingPalila
The solution with verbose_name in model field should do the trick.Huh

© 2022 - 2024 — McMap. All rights reserved.