Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django app post_save with sender=get_user_model()

Tags:

django

signals

I have a Django app that needs to receive the post_save signal when the user model is saved, without knowing about the main project directly. Here's the basic layout:

project/
    __init__.py
    settings.py
    models.py
app/
    __init__.py
    models.py
    signals.py

It must work with Django 1.6, so I can't use the ready() method. In app/__init__.py I have:

# app/__init__.py

import signals

And in app/signals.py:

# app/signals.py

from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=get_user_model())
def user_save_callback(sender, instance, **kwargs):
    ...

The installed apps in project/settings include:

# project/settings.py

INSTALLED_APPS = (
    ...
    'django.contrib.auth',
    'project',
    'app',
    ...

The custom user model is defined in project/models.py. The signals module is definitely being loaded with the correct user model (a quick print statement at the top of signals.py serves to demonstrate this).

However, my callback function never gets called when an instance of the user model is saved. The django-debug-toolbar helped me to verify that the receivers are not being registered. What gives? Any thoughts you might have are greatly appreciated ;)

----- EDIT -----

It ended up being a silly problem, so I'm not posting it as an Answer. It's a large project and there was another signal receiver somewhere else with the same name. The other one was getting defined after mine, which was overwriting it in the registry of receivers :P

I guess it's a lesson in naming conventions... If you're going to register a signal handler, name it something specific. Especially if there are multiple handlers for the same signal.

like image 768
stett Avatar asked Oct 15 '25 17:10

stett


1 Answers

I just updated a project from 1.7 to 1.8 and ran into this issue.

I was replacing old 'auth.User'and django.contrib.auth.models.Userreferences and stumbled upon the following error:

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

Reading through the traceback I found out that I did the following in my models.py:

models.signals.post_save.connect(create_user_profile, sender=get_user_model())

This is the second time I got that issue, so the following might be a solution to others. Simply replace the get_user_modelfunction with a string or setting:

models.signals.post_save.connect(create_user_profile, sender=settings.AUTH_USER_MODEL)
like image 61
Tobias Lorenz Avatar answered Oct 18 '25 06:10

Tobias Lorenz