Search code examples
djangosignalsuser-profile

Django create profile for user signal


im trying to create profile for user account using signals but after writing the codes is not creating at all

Django 3.0.5

users/models.py

from django.db import models
from django.contrib.auth.models import User
from PIL import Image


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

        img = Image.open(self.profile_image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.profile_image.path)

users/signals.py

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


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

users/apps.py

from django.apps import AppConfig


class UsersConfig(AppConfig):
    name = 'users'

    def ready(self):
        import users.signals

i check all the option on internet , but cant make this work , can any one help, maybe i missing something in my codes

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users',
    'courses',
    'crispy_forms',

]

i can see this message in apps.py:

Unused import statement 'import users.signals'

and in signals.py: Parameter 'sender' value is not used

Parameter '**kwargs' value is not used

Using PyCharm Proffesional


Solution

  • Replace

    INSTALLED_APPS = [
       ...
       'users',
       ...
    ]
    

    for

    INSTALLED_APPS = [
       ...
       'users.apps.UsersConfig',
       ...
    ]
    

    If you don't specify the path for the app configuration class, Django will use the base one as mentioned in the docs https://docs.djangoproject.com/en/3.0/ref/applications/. So your configuration was not being used which caused the signal file to not be imported during app registry and by consequence the signals were not registered.