Search code examples
pythondjangopython-2.7django-signals

Django, Add value to ManyToManyField when save changes of the model


I use Django 1.7.11. I have models:

#I use django-categories app here
class Category(CategoryBase):
   pass

class Advertisment(models.Model):
    title = models.CharField(max_length=255, blank=True)
    category = models.ForeignKey(Category, related_name='category')
    all_categories = models.ManyToManyField(Category, blank=True, related_name='all_categories')

I need field "all_categories" contains "category" and all it's parent categories. I tried to use post_save, but it doesn't change any value. It even doesn't change title field. It doesn't work when I create model throught admin interface and works with custom form.

@receiver(post_save, sender=Advertisment, dispatch_uid="update_stock_count")
def update_stock(sender, instance, **kwargs):     
 categ = instance.category     
 instance.all_categories.add(categ)          
 for parent in categ.get_ancestors():
            if parent not in instance.all_categories.all():
                     instance.all_categories.add(parent)

m2m_changed doesn't help too because ManyToManyField is empty and has no changes. How can I add a value from ForeignKey to ManyToMany field? What should I do in order to it works in admin interface.


Solution

  • I've found the solution. In admin class need to add a function save_model like this:

    class AdvertismentAdmin(admin.ModelAdmin):
       def save_model(self, request, obj, form, change):                   
          if obj.category:
            category_list=[]
            category = obj.category
            category_list.append(category)
            for parent in category.get_ancestors():
                if parent not in category_list:
                    category_list.append(parent)
            form.cleaned_data['all_categories'] = category_list            
            super(AdvertismentAdmin, self).save_model(request, obj, form, change)