I am attaching a method to the post_save signal of my Django model. This way I can clear some cached items whenever the model is modified.
The problem I am having is that the signal is being triggered twice when the model is saved. It doesn't necessarily hurt anything (the code will just gracefully error out) but it can't be right.
A quick example, just printing the model to the console (using the dev server):
from blog.models import Post
from django.db.models import signals
def purge_cache(sender, **kwargs):
print 'Purging %s' % sender
signals.post_save.connect(purge_cache, sender=Post)
This is using the stable 1.1.1 release of Django.
Updated Information:
With feedback from everyone's comments, I have modified my question because the issue is now discovering why the post_save is being triggered twice. My guess at the moment is that my models.py code is imported twice and that the post_save is getting connected multiple times.
What would be the best way to figure out why it is being imported/ran twice?
The save() function is used whenever the admin interface or the Django shell generates a model instance. Before storing the data in the database, we can change the save function to apply some constraints or fill some ready-to-use fields like SlugField.
save() calls the clean. This way the integrity is enforced both from forms and from other calling code, the command line, and tests. Without this, there is (AFAICT) no way to write a test that ensures that a model has a FK relation to a specifically chosen (not default) other model.
You can use pre_save for example if you have a FileField or an ImageField and see if the file or the image really exists. You can use post_save when you have an UserProfile and you want to create a new one at the moment a new User it's created.
Saving a Django model object updates all your columns every single time you call a save() method. To prevent this from happening you must be explicit.
Apparently, Python is sensitive to the way you import modules. In my case, it wasn't an issue with any of import code inside my blog application but an issue with the INSTALLED_APPS configuration, which I assume is used by Django to do an initial import.
Inside my blog application I was using imports such as:
from blog.models import *
My settings.py was configured as:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
...snip...
'sorl.thumbnail',
'mysite.blog',
)
The "mysite" prefix was added because I originally had import path issues when deploying the site. Later I fixed this issue (so it acted the same as the development server) by adding multiple paths in my WSGI script.
Removing the "mysite" prefix from the settings.py fixed the issue:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
...snip...
'sorl.thumbnail',
'blog',
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With