# manyToMany multipleChoiceField - how to add "checked" status

**URL:** <https://forum.djangoproject.com/t/manytomany-multiplechoicefield-how-to-add-checked-status/33228>\
**Category:** Using Django\
**Created:** [July 23, 2024, 10:32pm UTC](https://forum.djangoproject.com/t/manytomany-multiplechoicefield-how-to-add-checked-status/33228 "2024-07-23T22:32:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![perfecto25](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/perfecto25/32/12836_2.png) [@perfecto25](https://forum.djangoproject.com/u/perfecto25)\
**Post date:** [July 23, 2024, 10:32pm UTC](https://forum.djangoproject.com/t/manytomany-multiplechoicefield-how-to-add-checked-status/33228/1 "2024-07-23T22:32:30Z")

</div>

hello, Im trying to setup a monitoring app, which has HostGroups and Hosts

its a ManyToMany relationships, ie

“Prod” hostgroup can include host1, host2, host3  
“Webserver” hostgroup can include host1, host4, host5

so each host can be part of many Groups, and each Group can have many Hosts.

I setup my Model like this,

```auto

class Host(models.Model):
    monit_id = models.UUIDField(primary_key=True, editable=False)
    name = models.CharField(max_length=50, blank=True, null=True)

    def __unicode__ (self):
        return self.name

    class Meta:
        constraints = [models.UniqueConstraint(fields=["monit_id"], name="unique_monit_id")]

class HostGroup(models.Model):
    name = models.CharField(max_length=50, blank=False, null=False)
    description = models.CharField(max_length=100, blank=True, null=True)
    host = models.ManyToManyField(Host, blank=True)

    def __unicode__ (self):
        return self.name

    class Meta:
        constraints = [models.UniqueConstraint(fields=["name"], name="unique_hostgroup_name")]

```

my Form is appending Host choices by doing a query on the Host object

```auto
class HostGroupForm(forms.ModelForm):
    class Meta:
        model = HostGroup
        fields = " __all__"

    name = forms.CharField(max_length=40, required=True)
    description = forms.CharField(max_length=50, required=False)
    host = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple)

    def __init__ (self, *args, **kwargs):
        super(HostGroupForm, self). __init__ (*args, **kwargs)
        self.fields['host'].choices = [(host.monit_id, host.name) for host in Host.objects.filter(approved=True)]

```

and finally my view saves the incoming form and creates a ManyToMany relationship in the M2M table that gets created automatically

```auto
if request.method == "POST":
        obj = HostGroup.objects.get(pk=id)
        form = HostGroupForm(request.POST, instance=obj)
        if form.is_valid():
            obj = form.save(commit=True)
            for h in request.POST.getlist('host'):
                obj.host.add(h)

```

I can see the relationship created from the obj.host.add(h) line

 ![ksnip_20240723-182806](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/a/7/a7084a1d8fb7d3b73505d67135bb275623acc85e.png)

what I cant figure out is how to display the selected Hosts in the Group when the form is presented back to the template, right now it displays a blank list of all hosts from the query in the Form class,

how can i make it automatically “check” a checkbox if the host is in a Many2Many relationship with a HostGroup ?

 ![ksnip_20240723-183106](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/5/d/5d8c91b6ec8265f16a859c4cb18ec5f41e918a27.png)

Idea is to show the user all possible hosts that he can add to the HostGroup, and show which hosts are already part of this HostGroup (with a checkmark)

thanks

---

<div class="post-metadata">

**Author:** ![white-seolpyo](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/white-seolpyo/32/22386_2.png) [@white-seolpyo](https://forum.djangoproject.com/u/white-seolpyo)\
**Post date:** [July 24, 2024, 1:21am UTC](https://forum.djangoproject.com/t/manytomany-multiplechoicefield-how-to-add-checked-status/33228/2 "2024-07-24T01:21:15Z")

</div>

maybe it help…

> **[The Django admin site | Django documentation](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects)**
>
> The web framework for perfectionists with deadlines.

---

<div class="post-metadata">

**Author:** ![anefta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/anefta/32/10649_2.png) [@anefta](https://forum.djangoproject.com/u/anefta)\
**Post date:** [July 25, 2024, 9:25am UTC](https://forum.djangoproject.com/t/manytomany-multiplechoicefield-how-to-add-checked-status/33228/3 "2024-07-25T09:25:51Z")

</div>

> [@perfecto25](#):
>
> what I cant figure out is how to display the selected Hosts in the Group when the form is presented back to the template, right now it displays a blank list of all hosts from the query in the Form class,
> 
> how can i make it automatically “check” a checkbox if the host is in a Many2Many relationship with a HostGroup ?

To ensure that the checkboxes are automatically checked for hosts that are already part of the `HostGroup` when the form is presented back to the template, you need to set the initial values for the `host` field in the form. This can be done in the ` __init__ ` method of your `HostGroupForm`.

Here is the updated code for your form:

```class
    class Meta:
        model = HostGroup
        fields = " __all__"

    name = forms.CharField(max_length=40, required=True)
    description = forms.CharField(max_length=50, required=False)
    host = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple)

    def __init__ (self, *args, **kwargs):
        super(HostGroupForm, self). __init__ (*args, **kwargs)
        self.fields['host'].choices = [(host.monit_id, host.name) for host in Host.objects.filter(approved=True)]
        
        # If an instance is provided, set the initial values for the host field
        if 'instance' in kwargs:
            self.fields['host'].initial = [host.monit_id for host in kwargs['instance'].host.all()]

```

In your view, make sure to pass the instance of `HostGroup` to the form when you are editing an existing group:

```auto
if request.method == "POST":
    obj = HostGroup.objects.get(pk=id)
    form = HostGroupForm(request.POST, instance=obj)
    if form.is_valid():
        obj = form.save(commit=True)
        obj.host.set(request.POST.getlist('host'))
else:
    obj = HostGroup.objects.get(pk=id)
    form = HostGroupForm(instance=obj)

return render(request, 'your_template.html', {'form': form})

```
