4

I have a problem with a post_save function. The function is correctly triggered but the instance doesn't contains the value insereted. I checked the function using ipdb and there is nothing wrong. Simply the ManyToManyField is empty.

The code:

@receiver(post_save, sender=Supplier)
def set_generic_locations(sender, instance, **kwargs):
    """ Set the generic locations for the NEW created supplier.
    """
    created = kwargs.get('created')
    if created:
        glocations = LocationAddress.get_generic_locations()

        for location in glocations:
            instance.locations.add(location)

        instance.save()

The field used in the instance:

locations = models.ManyToManyField(LocationAddress, blank=True)​

I don't understand why, but the locations is always empty.

I use django 1.8.8

UPDATE

The problem is the django admin. I found an explanation here: http://timonweb.com/posts/many-to-many-field-save-method-and-the-django-admin/

The code that solve the problem in the django admin

def save_related(self, request, form, formsets, change):
    super(SupplierAdmin, self).save_related(request, form, formsets, change)
    form.instance.set_generic_locations()
Karim N Gorjux
  • 2,880
  • 22
  • 29

2 Answers2

3

ManyToManyFields work a little bit differently with signals because of the difference in database structures. Instead of using the post_save signal, you need to use the m2m_changed signal

awwester
  • 9,623
  • 13
  • 45
  • 72
  • 1
    I need to add reference to a model after its creation. I don't need to monitor the m2m change. – Karim N Gorjux Jan 27 '16 at 20:48
  • `M2M`s are saved after instances are saved and there won't be any record in `post_save` method. Checking this answer that explains why: http://stackoverflow.com/questions/23795811/django-accessing-manytomany-fields-from-post-save-signal?answertab=votes#tab-top – Shang Wang Jan 27 '16 at 22:34
  • 1
    "m2m_changed is sent when a ManyToManyField is changed on a model instance." It's not my case, I want to triggered it in the creation of a model instance. – Karim N Gorjux Jan 28 '16 at 14:42
0

For manytomanyfield, you have to save first your parent object () and then add your

steep2000
  • 13
  • 1
  • 5