Jay P.
Jay P.

Reputation: 2590

Django admin save() doesn't get data from ManyToManyField

I'm trying to get chosen objects from affiliate_networks in Django admin when the user clicks the submit button.

When I choose one from affiliate_networks and submit it, the console prints an empty of affiliate_networks, and then I come back to the page and the chosen object is stored properly. So, I submit it again, then the console prints the chosen object. save() only receives objects that are already stored, not objects that I choose before saving.

Is there a way, that I can have save() to notice affiliate_networks to have any object chosen?

class Store(models.Model):
    ...
    affiliate_networks = models.ManyToManyField(AffiliateNetwork, blank=True)

    def save(self, *args, **kwargs):
        print(self.affiliate_networks.all())

Upvotes: 0

Views: 226

Answers (1)

Paul Griffin
Paul Griffin

Reputation: 133

You can't do it in save() - as you have discovered, Django admin doesn't save ManyToMany objects until afterwards. You need to do it in the save_related method of ModelAdmin. See https://timonweb.com/posts/many-to-many-field-save-method-and-the-django-admin/

In admin.py:

...

class StoreAdmin(admin.ModelAdmin):

    def save_related(self, request, form, formsets, change):
        super(StoreAdmin, self).save_related(request, form, formsets, change)
        print(form.instance.affiliate_networks.all())

...

admin.site.register(Store, StoreAdmin)

Upvotes: 1

Related Questions