ManyToMany relationship in formset

I can’t figure out how to save ManyToMany field in formset. I have these models:

class Mixture(models.Model):
    mixture_name = models.TextField(
        max_length = 2000,
    )
    public_name = models.TextField(
        max_length = 2000,
    )

class OtherIdentifier(models.Model):
    mixture = models.ForeignKey(
        Mixture,
        on_delete = models.CASCADE,
    )
    name = models.TextField(
        max_length = 2000,
        null=True,
        blank=True,
    )
    country = models.ManyToManyField(
        Country,
    )

class Country(models.Model):
    name = models.CharField(
    )

I created formset for OtherIdentifier this way:

class OtherIdentifierForm(ModelForm):
    class Meta:
        model = OtherIdentifier
        fields = [
            'name',
            'country',
        ]

OtherIdentifierFormset = inlineformset_factory(
    Mixture, OtherIdentifier, form = OtherIdentifierForm,
    extra = 0,
    can_delete = True, can_delete_extra = True,
)

I save the formset in the view:

class MixtureEditParentView():
    model = Mixture
    form_class = MixtureForm
    template_name = 'mixture_form.html'

    def form_valid(self, form):
        other_identifier_formset = self.get_other_identifier_formset()

        if not other_identifier_formset.is_valid():
            return self.render_to_response(self.get_context_data(form=form))
        # save form
        self.object = form.save()
        # save formset
        self.other_identifier_formset_valid(other_identifier_formset)
        return redirect(self.get_success_url())

    def other_identifier_formset_valid(self, other_identifier_formset):
        other_identifiers = other_identifier_formset.save(commit=False)
        for obj in other_identifier_formset.deleted_objects:
            obj.delete()
        for other_identifier in other_identifiers:
            other_identifier.mixture = self.object
            other_identifier.save()

Only the ‘name’ of OtherIdentifier is saved, not the ‘country’. What am I misssing?

When you use commit=False in the save process, you need to use the save_m2m function to save the many-to-many relationships after doing the save().

See the docs at Saving objects in the formset.

Thank you. I really appreciate your help! It works now.