[django] How to add data into ManyToMany field?

I can't find it anywhere, so your help will be nice for me :) Here is that field:

categories = models.ManyToManyField(fragmentCategory)

FragmentCategory:

class fragmentCategory(models.Model):

        CATEGORY_CHOICES = (
                        ('val1', 'value1'),
                        ('val2', 'value2'),
                        ('val3', 'value3'),
                        )

        name = models.CharField(max_length=20, choices=CATEGORY_CHOICES)

Here is the form to send:

<input type="checkbox" name="val1" />
<input type="checkbox" name="val2" />
<input type="checkbox" name="val3" />

I tried something like this:

categories = fragmentCategory.objects.get(id=1),

Or:

categories = [1,2]

This question is related to django django-models

The answer is


In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)