Jpb
Jpb

Reputation: 45

Django - Using forms.CheckboxSelectMultiple

I'm trying to create a multi-select list of checkboxes for names in a database.

I thought I could do the below in the from, and do some kind of loop in the template to render each name, but noting I try works. Is this the correct approach, any clues on how to render this in the template?

Thanks

from django import forms
from .models import Player

class PlayerForm(forms.Form):

    team = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        choices=[Player.objects.all()]
    )


from django.db import models

class Player(models.Model):
    lname = models.CharField(max_length=10, verbose_name='Last Name')
    fname = models.CharField(max_length=10, verbose_name='First Name')
    wins = models.SmallIntegerField(default=0, null=True, blank=True)
    loss = models.SmallIntegerField(default=0, null=True, blank=True)


    def __str__(self):
        return "{}".format(self.lname)

    class Meta:
        ordering = ['lname']

Upvotes: 1

Views: 2240

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

Not entirely. If you need to select a option among model options, you should use a ModelMultipleChoiceField field [Django-doc]. This will not only make it more convenient to work with data, but it will furthermore each time query the database, such that, if you add a new Player, one can select that one.

You thus can implement this as:

class TeamForm(forms.Form):
    team = forms.ModelMultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        queryset=Player.objects.all()
    )

It might furthermore be better to name your form TeamForm, since you here do not create/update/... a Player, but you select a team.

Upvotes: 1

Related Questions