prefilled SelectMultiple form field

Hi all,
I’m tring to build a prefilled form using a forms.ModelMultipleChoiceFiled with CheckboxSelectMultiple widget. The singles choices are selected based on a boolean db column. I thought to change the attrs={“checked”:“”} every “input” instance, but I don’t know how to loop on choices.

The model

from django.db import models

class MyModel(models.Model):
   id = models.AutoField(db_column="ID", primary_key=True)
   is_cheched = models.BooleanFields()
   value = models.CharField()

The form

from django import forms
from myapp.models import MyModel

class MyForm(forms.Form):
   qs = MyModel.object.value_list("id","value")
   qsa = MyModel.object.value_list("id", "is_checked")
   myfield = forms.ModelMultipleChoiceField(queryset=qs, widget=form.CheckboxSelectMultiple)
   extrafield = forms.CherField(widget=forms.Textarea)

   def __init__(self, *args, **kwargs):
      super(MyForm, self).__init__(*args, **kwargs)
      for id, is_checked in self.qsa:
         if is_checked is True:
            #this obviously doesn't work as I need.
            self.fields["myfield"].widget.attrs["checked"] = ""

The output I need

<form action="some_action">
  <input type="checkbox" id="1" name="1" value="value_1">
  <label for="value_1"> value_1</label><br>
  <input type="checkbox" id="2" name="2" value="value_2">
  <label for="value_2"> value_2</label><br>
  <input type="checkbox" id="3" name="3" value="value_3">
  <label for="value_3" checked="checked"> value_3</label><br><br>
  <input type="submit" value="Submit" >

Unless there’s more context to this that you have edited out, I don’t see where this is in the category of a Model Multiple Choice field. You’re not showing these selections as being related to some other model.

For specifically what you have shown here, I’d be creating a formset, where each checkbox is a is a single field form for each instance of that model.

If you didn’t want to go the formset route, you could still dynamically create individual fields - one per instance of MyModel.

As a side note, your qsa queryset is performing that query at the Model layer, which means it would be executed once when the model is imported and not each time the model is instantiated. (This is different from the queryset attribute of the ModelMultipleChoiceField which is explicitly defined as being evaluated when the form is rendered.) What this means is that you would want to move the qsa query to inside the __init__ method.