I have created a modelformset for voting on multiple subtitles. It looks like this:
I want to change the "Vote:" label to the names of the different subtitles instead (so if the subtitles are A, B and C, A should be before the first field, B for the second field etc.). How can I change this?
The modelformset is created in the views.py like this:
VoteFormSet = modelformset_factory(YesNoVote, form=YesNoVotingForm, extra=3)
YesNoVotingForm looks like this:
class YesNoVotingForm(forms.ModelForm):
class Meta:
model = YesNoVote
fields = ['vote',]
widgets = {
'vote': forms.Select(attrs={"required": True}),
}
and this is the yesnovote model:
class YesNoVote(models.Model):
subtitle = models.CharField(max_length=128)
vote = models.CharField(choices=choices, max_length=10)
user = models.ForeignKey(User, on_delete=models.CASCADE, db_constraint=False, related_name="yesnovote_user", null=True)
election = models.ForeignKey(YesNoElection, on_delete=models.CASCADE, related_name="yesnovote")
def __str__(self):
return f"{self.user} stemde {self.vote} bij {self.subtitle} (vallend onder {self.election})"
and this is the html page:
<form method="post">
{{ formset.management_data }}
{% csrf_token %}
{% for form in formset %}
{{ form }}
<br>
{% endfor %}
<button type="submit" name = "voting" class="btn btn-primary save">Submit</button>
Let op: Je kunt je stem niet meer wijzigen.
</form>
So if you have exact number of formsets try:
in views.py add formset for modelformset_factory:
VoteFormSet = modelformset_factory(YesNoVote, form=YesNoVotingForm, extra=3, formset=YesNoVoteModelFormSet)
in forms.py create:
class YesNoVoteModelFormSet(forms.BaseInlineFormSet):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
label_list = ["A", "B", "C"]
for num, form in enumerate(self.forms):
form.fields["vote"].label = label_list[num]
for more info go here https://docs.djangoproject.com/en/4.0/ref/forms/models/#modelformset-factory