How to increase 1 unit a integerfield when upload a image?
I have a question. I have a user model and it has profile_image and profile_image_quantity fields. Can I increase my value of profile_image_quantity when uploading a image?
My user model:
class User(AbstractBaseUser):
username = models.CharField(max_length=30, verbose_name="Username", help_text="Be carefully while choosing username. If you want change your username you have to pay money")
email = models.EmailField(help_text="Your active email adress", verbose_name="Email", unique=True)
first_name = models.CharField(max_length=20, verbose_name="First Name", help_text="Your first name")
last_name = models.CharField(max_length=20, verbose_name="Last Name", help_text="Your last name")
birthday = models.DateField(blank=False, null=True, help_text="Your birthday")
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now=True)
is_staff = models.BooleanField(verbose_name="Staff", default=False)
is_admin = models.BooleanField(verbose_name="Admin", default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_verified_account = models.BooleanField(default=False)
is_verified_email = models.BooleanField(default=False, help_text="Your email still isn't verified")
status = models.CharField(choices=status, default='Online', max_length=20, help_text="Your currently status")
profile_image_quantity = models.IntegerField(default=0)
profile_image = models.ImageField(upload_to=get_profile_image_path, verbose_name="Profile Image", default=default_profile_image_path, blank=True)
My get_profile_image_path function:
def get_profile_image_path(instance, filename):
ext = filename.split('.')[-1]
user = User.objects.get(id=instance.id)
user.profile_image_quantity += 1
user.save()
return f"User/{user.pk}/profile_images/{user.profile_image_count}.{ext}"
I would recommend you override the save method on your model accompanied by overridden init method to store a cached version of the original profile image to check against after the form is submitted.
Then it doesn't matter when or where you edit the user model, if you changed it, and you saved it, it will increment by 1
class User(AbstractBaseUser):
...
def __init__(self, *args, **kwargs):
self._original_profile_image = self.profile_image
super().__init__(*args, **kwargs)
def save(self):
if self.image_profile and not self._original_image_profile:
self.profile_image_quantity += 1
super().save()