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.

Local Development Settings File

Posted: March 17th, 2010 | Author: Arif Harbott | Filed under: Django | Tags: , | No Comments »

If you want to have local development settings in your Django project but don’t fancy having multiple versions of settings.py then you can use the following snippet at the end of your settings.py file.

# Import server specific settings
try:
    from settings_local import *
except ImportError:
    pass

Then put any local development settings in a file called settings_local.py and you can override anything from settings.py.
If settings_local.py does not exist on your production server no error is thrown.