Home > Blockchain >  How can I populate a Django ChoiceField with attributes of an object?
How can I populate a Django ChoiceField with attributes of an object?

Time:04-22

I have a Election and Candidate object model like so:

class Election(models.Model):
id = models.IntegerField(primary_key=True, unique=True)
name = models.CharField(max_length=80)
region = models.CharField(max_length=80)
candidates_count = models.IntegerField()
total_votes_cast = models.IntegerField()

def __str__(self):
    return self.name


class Candidate(models.Model):
    id = models.IntegerField(primary_key=True, unique=True)
    name = models.CharField(max_length=80)
    party = models.CharField(max_length=80)
    election_id = models.IntegerField()
    vote_count = models.IntegerField()

def __str__(self):
    return self.name

I have a form to create a new candidate, like so:

class AddNewCandidateForm(forms.Form):
PARTY_CHOICES = [
    (1, "Party 1"),
    (2, "Party 2"),
    (3, "Party 3"),
    (4, "Party 4"),
    (5, "Party 5"),
    (6, "Other")
]

candidate_name = forms.CharField(
    max_length=80,
    required=True,
    label='Candidate Name'
)

candidate_party = forms.ChoiceField(
    label='This candidates party',
    required=True,
    widget=forms.Select(),
    choices=PARTY_CHOICES
)

candidate_election = forms.ChoiceField(
    label="The election that this candidate is participating in",
    required=True,
    widget=forms.Select()
)

I want to populate the candidate_election ChoiceField with the name attribute of all of existing Election objects in the database.

What is the best way to do this? I'm struggling with ways to figure out how to make a 2-tuple for the ChoiceField to accept.

Thanks!

CodePudding user response:

Update your candidate_election variable to this

candidate_election = forms.ChoiceField(
    label="The election that this candidate is participating in",
    required=True,
    widget=forms.Select()
    choices=[(e.id,e.name) for e in Election.objects.all()]
)
  • Related