'Instance in upload_image function django framework
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}"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
