Home > Net >  Django save() method doesn't save in upload_to function
Django save() method doesn't save in upload_to function

Time:02-10

I have a issue in my code. I have a user model and it has a profile_image field with ImageField. I defined a profileImageRoot() function and equalized it to upload_to argument of ImageField. I have profile_image_count IntegerField and it increases 1 unit when image is uploaded in profileImageRoot(). I try save the value of profile_image_count on my database but save() method doesn't save. My source code:
User model:

class User(AbstractBaseUser):
    username                = models.CharField(max_length=20, unique=True, verbose_name="Username")
    email                   = models.EmailField(unique=True, verbose_name="Email", help_text="Email you actively use")
    first_name              = models.CharField(max_length=20)
    last_name               = models.CharField(max_length=20)
    date_of_birth           = models.DateField(blank=False)
    date_created            = models.DateTimeField(auto_now_add=True)
    last_login              = models.DateTimeField(auto_now=True)
    profile_image           = models.ImageField(upload_to=profileImageRoot)
    profile_image_count     = models.IntegerField(default=0)
    spent_money             = models.FloatField(default=0)

    is_active               = models.BooleanField(default=True)
    is_admin                = models.BooleanField(default=False)
    is_staff                = models.BooleanField(default=False)
    is_superuser            = models.BooleanField(default=False)
    is_verified             = models.BooleanField(default=False)

    objects = UserManager()


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ('username', 'first_name', 'last_name', 'date_of_birth')

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

    def get_full_name(self):
        return f"{self.first_name} {self.last_name}"
    
    def is_birthday(self):
        if timesince(self.date_of_birth, datetime.today()) == datetime(day=0, month=0):
            return True
        else:
            return False


    def verify(self):
        self.is_verified = True

    def __str__(self):
        return self.get_full_name()

profileImageRoot():

def profileImageRoot(instance, filename):
    user = User.objects.get(pk=instance.pk)
    ext = filename.split(".")[-1]
    user.profile_image_count  = 1
    print(user.profile_image_count)
    user.save()
    return f"{user.username}/profile_image/{user.profile_image_count}.{ext}"

CodePudding user response:

This is likely because your original instance contains the old value for profile_image_count. Since the saving process first needs to call profileImageRoot() and then write data from instance to database, your increased value for profile_image_count is overriden with the old value.

Try to also increase instance.profile_image_count in profileImageRoot().

This, however, seems like a poor solution overall. If you want some ordering in file names for profile images consider using timestamps or alike. Besides there's no guarantee that profileImageRoot() will be called just once per save() call, or that it won't be called unless new image is uploaded.

  • Related