Django conditional post save signal not working

I have a model for user profiles that has a post save signal that auto creates a user profile whenever a new user is created. I don't want the post save signal to create a user profile when a new superuser is created. So far I have not been able to get this to work.

Any ideas about how to fix this?

the model:

from django.db import models
from tinymce import models as tinymce_models
from accounts.models import CustomUser
from phone_field import PhoneField
from constrainedfilefield.fields import ConstrainedFileField
import os
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import sys
from PIL import Image
from django.db.models.signals import post_save
import PIL

class UserProfile(models.Model):
    user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE)
    preferred_name = models.CharField(null=True, blank=True, max_length= 75)
    pronouns = models.CharField(null=True, blank=True, max_length= 40)
    phone = PhoneField(blank=True, help_text='Contact phone number')
    job_title = models.CharField(null=True, blank=True, max_length= 75)
    birthdate = models.DateField(null=True, blank=True)
    bio = tinymce_models.HTMLField(null=True, blank=True)
    profile_image = ConstrainedFileField(
        null=True,
        blank=True,
        upload_to='projects/employee_profiles',
        content_types=['image/png', 'image/jpg', 'image/jpeg', 'image/gif'],
        max_upload_size=2097152,
    )

    def save(self, *args, **kwargs):
        super(UserProfile, self).save(*args, **kwargs)
        if self.profile_image:
            if os.path.exists(self.profile_image.path):
                image = Image.open(self.profile_image)
                outputIoStream = BytesIO()
                basewidth = 100
                wpercent = basewidth / image.size[0]
                hsize = int(image.size[1] * wpercent)
                imageTemproaryResized = image.resize((basewidth, hsize))
                imageTemproaryResized.save(outputIoStream, format='PNG')
                outputIoStream.seek(0)
                self.profile_image = InMemoryUploadedFile(outputIoStream, 'ConstrainedFileField',
                                                      "%s.png" % self.profile_image.name.split('.')[0], 'image/png',
                                                      sys.getsizeof(outputIoStream), None)
                super(UserProfile, self).save(*args, **kwargs)


    def save(self, *args, **kwargs):
        if self.profile_image:
            super().save()
            img = Image.open(self.profile_image.path)
            if img.height  > img.width:
                # make square by cutting off equal amounts top and bottom
                left = 0
                right = img.width
                top = (img.height  - img.width) / 2
                bottom = (img.height  + img.width) / 2
                img = img.crop((left, top, right, bottom))
                # Resize the image to 50X50 resolution
                if img.height > 60 or img.width > 60:
                    output_size = (60, 60)
                    img.thumbnail(output_size)
                    img.save(self.profile_image.path)
            elif img.width > img.height:
                # make square by cutting off equal amounts left and right
                left = (img.width - img.height) / 2
                right = (img.width + img.height) / 2
                top = 0
                bottom = img.height
                img = img.crop((left, top, right, bottom))
                # Resize the image to 50X50 resolution
                if img.height > 60 or img.width > 60:
                    output_size = (60, 60)
                    img.thumbnail(output_size)
                    img.save(self.profile_image.path)


        super(UserProfile, self).save(*args, **kwargs)


    def create_user_profile(sender, instance, created, **kwargs):
        if (created) and (not instance.is_superuser):
            UserProfile.objects.create(user=instance)
            post_save.connect(create_user_profile, sender=CustomUser)

    def __str__(self):
      return str(self.user)

Ok the soluation is very easy the instance in the post save means the user profile which is dont have is_superuser method on it and it always return None and this result to False.

Soluation: Access the user from the instance and then check if he is superuser or not by change the condition to:

if created and not instance.user.is_superuser:

Back to Top