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" >
</form>