4

I'm trying to write some code that sends an email every time one of the users modifies a model object. Currently, I'm working on having the one of the methods in models.py receive a post_save signal. I realize it's a well known fact that the post_save signal is usually sent twice, thus, the workaround is to utilize the dispatch_uid parameter. I have done this, but for some strange reason, I continue to receive two signals. Here's the code in my app's model.py file.

from django.db import models
from django.db.models.signals import post_save

def send_email(sender, **kwargs):
      print "Signal sent." #just a placeholder

post_save.connect(send_email, dispatch_uid="unique_identifier")

class Library_Associates (models.Model):
      first_name = models.CharField(max_length = 200)
      last_name = models.CharField(max_length = 200)

  department_choices = (
        ('ENG', 'Engineering'),
        ('ART', 'Arts and Sciences'),
        ('AFM', 'Accounting and Financial Managment'),
        ('MAT', 'Mathematics'),
  )

  department = models.CharField(max_length = 3, choices = department_choices, default = 'ENG')

  pub_date = models.DateTimeField ('date published')

  def __unicode__(self):
        return self.first_name

  class Meta:
        verbose_name_plural = 'Library Associates'

class Info_Desk_Staff (models.Model):
      first_name = models.CharField(max_length=50)
      last_name = models.CharField(max_length=50)
      salary = models.IntegerField()
      hours_worked = models.IntegerField()

      def __unicode__(self):
            return self.first_name

      class Meta:
            verbose_name_plural = 'Info Desk Staff'

I already restarted the server several times, reset/deleted all the data for the app and I continue to still receive two signals. Is there something inherently wrong with my code? Any suggestions or insight would be greatly appreciated! Thanks!

4
  • It might be helpful to see the view/form code where the object is being saved. Occasionally, you can run into a situation where you actually save the object twice without realizing it. Feb 6, 2013 at 18:40
  • Forgive me if I say something that doesn't correlate, I'm still new to Django. The view/form code that you're talking about refers to the views.py that is made automatically when I created the app, correct? In that case, my view.py file is completely empty, untouched.
    – Kenny
    Feb 6, 2013 at 18:51
  • So are you just using the Django admin to modify your objects? Otherwise, where are you saving it? Feb 6, 2013 at 18:55
  • Yep, I have an admin.py file in the same app folder. Its contents literally consists of 4 lines. Two model imports and two admin.site.register("model_name"). I'm using the default form I believe? The one with the 3 save options. As to where I'm saving it, I think the data is being saved in "test_database.db" file I created in the project directory.
    – Kenny
    Feb 6, 2013 at 19:02

1 Answer 1

6

Your problem comes from the fact that each time you modify an object via the admin interface, admin app creates the django.contrib.admin.models.LogEntry instance that represents changes made.

Because you are listening to post_save on all objects, your listener is called twice - once for your model, and the second time for the LogEntry model.

List of possible solutions includes:

  1. Registering your listener separately for each of your models (e.g. select your models somehow and do it in a loop) using the sender argument in the post_save method.

    for model in get_models():
        post_save.connect(send_email, sender = model, dispatch_uid='unique_identifier')
    
  2. Check if the sender sent to the listener is not an instance of django.contrib.admin.models.LogEntry

    from django.contrib.admin.models import LogEntry
    ...
    
    def send_email(sender, **kwargs):
        if isinstance(sender, LogEntry):
            return
    
  3. Give your models a common super class and use that for testing in the listener

    class MyModel(models.Model):
        pass
    
    class Library_Associates (MyModel):
        ...
    class Info_Desk_Staff (MyModel):
        ...
    
    def send_email(sender, **kwargs):
        if not isinstance(sender, MyModel):
            return
    
5
  • I have attempted to implement the second solution you outlined. The isinstance(sender, LogEntry) came back as False for both signals. I'm completely lost. Could there perhaps be another reason for the double signal? I heard the duplicate post_save signal is the result of the way Django/Python imports modules.
    – Kenny
    Feb 12, 2013 at 16:12
  • That's weird. I checked it earlier on Django 1.4 and that was the reason for a double signal. What version are you using? Just put a print sender in the signal handler and let's just see what you get.
    – zifot
    Feb 12, 2013 at 21:43
  • Ah, what you know. The print sender gave me one signal from my models and one signal from the LogEntry. You were right! Guess the issue is probably my if statement in the second solution wasn't written correctly. def send_email(sender, **kwargs): if isinstance(sender, LogEntry): print "LogEntry signal received." return else:
    – Kenny
    Feb 13, 2013 at 14:26
  • I did the import using: from django.contrib.admin.models import LogEntry. Then under the send_email function, I wrote the if statement: if isinstance(sender, LogEntry): return, else: #code for sending the email. I put a print statement under the else statement code, and that came up twice when I saved. It's somehow ignoring the LogEntry if statement.
    – Kenny
    Feb 13, 2013 at 14:51
  • Ah, I think I understand the issue. The isinstance isn't working because both signals are the same model 'type'. However, the 'value' of sender is different for each one.
    – Kenny
    Feb 13, 2013 at 15:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.