Get m2m/many to many after save (save_model)

Posted: March 17th, 2010 | Author: Davo | Filed under: Django | Tags: , | 2 Comments »

The scenario is the following:

I have an object which has a ManyToMany field and when I save that object in the admin I want to know the previous values and the new ones.

A simple Note model:

from django.db import models
class Note(models.Model):
    name = models.CharField(max_length=100)
    languages = models.ManyToManyField('languages.Language') # can be anything else...

And this is the following admin manager for Note

from django.contrib import admin
from yourapps.models import Note
class NoteAdmin(admin.ModelAdmin):
    ....
    def save_model(self, request, obj, form, change):
        print 'Current languages : '
        print obj.languages.all()

        if change:
            languages = form.cleaned_data['languages']
            print 'New languages : '
            print languages

        # call the admin model save.
        super(NoteAdmin, self).save_model(request, obj, form, change)        

admin.site.register(Note, NoteAdmin)

The save_model() function has 4 arguments

  • request the request object
  • obj the current instance of the object (in our case Note)
  • form the form which was submitted in the admin
  • change a boolean if set to True then it means the object is changed(saved) instead of created.