ManyToMany field not saved when using Django admin
In django 2,1,4 my solution was to use save_related()
def save_related(self, request, form, formsets, change):
super().save_related(request, form, formsets, change)
form.instance.permissions.add(request.user)
So it turns out the above was not the correct way to implement it. The code belonged in StoreAdmin, by overriding model_save().
This is how I solved it:
class StoreAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if obj.copy_holidays_from:
form.cleaned_data['holidays'] = obj.copy_holidays_from.holidays.all()
super(StoreAdmin, self).save_model(request, obj, form, change)
I probably ran into this same behaviour just today and yes, you are correct in assuming it's related to how django handles the data.
The django admin makes the changes to a ManyToMany field separately from changing the actual object. (Remember that the m2m is saved in a different database table).
In my case if I didn't select anything in the ManyToMany field in the admin site, this would translate into a clear()-operation on the ManyToMany relation. Everything you do in the save()-method is immediately removed by this clear. Same thing with stuff I did in the post_save signal handler.
The solution (for me) was to separate the ManyToMany-field into an inline so it doesn't automatically get saved as empty when modifying the object.