yvl
yvl

Reputation: 660

Django DRF signal, post_save is not firing

I am having a issue about creating a token. I setup DRF's TokenAuthentication but when I sign up a user signal is not firing.

in settings.py

INSTALLED_APPS = [
    ..
    'rest_framework',
    'rest_framework.authtoken',
    ..
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}

inside account app, this signals.py

from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token


@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    print("fired")
    if created:
        Token.objects.create(user=instance)

I can save the new user but for new user can't create a token. print("firing") not running as well. What am I missing here?

Upvotes: 0

Views: 1142

Answers (1)

yvl
yvl

Reputation: 660

I solved the problem by registering signals.py inside the apps.py

from django.apps import AppConfig

class AccountConfig(AppConfig):
    name = 'account'

    def ready(self):
        import account.signals

And also must to add account app and also signals into installed apps like below.

INSTALLED_APPS = [
   ...
    'account.apps.AccountConfig', # here
    'rest_framework',
    'rest_framework.authtoken',
   ...
]

then I can finally got my token.

Upvotes: 2

Related Questions