Question

I am sure this is something stupid that I cannot see, but here is what I have

def save(self, *args, **kwargs):
    print self.sites.all()
    super(Article, self).save(*args, **kwargs)
    self.sites.add(Site.objects.get(pk=1))
    print self.sites.all()

Which prints

[<Site: site2.co.nz>, <Site: site3.co.nz>]
[<Site: site2.co.nz>, <Site: site3.co.nz>, <Site: site1.co.nz>]

but site1.co.nz is not being persisted in the m2m relationship.

Was it helpful?

Solution

Looks like django admin saves the m2m separately which clears the m2m data in my custom save method.

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_related

class MyModelAdmin(admmin.ModelAdmin):
    def save_related(self, request, form, *args, **kwargs):
        super(ArticleAdmin, self).save_related(request, form, *args, **kwargs).
        obj = form.instance
        obj.sites.add(Site.objects.get(id=1))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top