'How do I display only the checked checkboxes in a forms.CheckboxSelectMultiple?

I get list of all checkboxes in CheckboxSelectMultiple (checked and unchecked) but I need to get list only checked checboxes. How to do it?

I have a form.py:

class ProfileForm(forms.ModelForm):
   class Meta :
       fields = [ 'categories', ]
       widgets = {'categories': forms.CheckboxSelectMultiple(attrs = { "class": "column-checkbox"})}

models.py:

class Profile(models.Model):
    categories = models.ManyToManyField(Category, max_length=50, blank=True, 
    verbose_name='Category')


Solution 1:[1]

Change the field's choice or queryset attribute to dynamically limit the choices depending on the current object.

You can change choices in the view:

# views.py

form = ProfileForm(instance=profile)
form.fields['categories'].choices = [(category.pk, category.name) for category in profile.categories.all()]

Or you can change queryset in the view:

# views.py

form = ProfileForm(instance=profile)
form.fields['categories'].queryset = profile.categories.all()

Or you do it in the form's __init__() method:

# models.py

class ProfileForm(forms.ModelForm):
    ...
       
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['categories'].queryset = self.instance.categories.all()

            # Or alternatively using choices
            #self.fields['categories'].choices = [(category.pk, category.name) for category in self.instance.categories.all()]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Qtng