models.py
def content_file_name(instance, filename):
extension = filename.split(".")[-1]
ext2 = filename.replace(extension, "png")
og_filename = ext2.split('.')[0]
og_filename2 = ext2.replace(og_filename, str(instance.id))
path = os.path.join(settings.BASE_DIR, 'static/images/profile',)
dir_list = os.listdir(path)
for i in dir_list:
if i == og_filename2:
dir_list.pop(-1)
dir_list.append(og_filename2)
return os.path.join('profile/', og_filename2)
return os.path.join('profile/', og_filename2)
class User(models.Model):
mobile = models.CharField(max_length=20)
otp = models.CharField(max_length=6)
name = models.CharField(max_length=200)
username = models.CharField(max_length=200)
profile_dp = models.ImageField(upload_to = content_file_name ,null=True, blank=True)
profile_url = models.CharField(max_length=200)
Through the content_file_name() function when i upload an image its name should change to this format user's id.png. and then when i again upload an image to the same field the last image should get deleted and the new image with the same name should get uploaded.
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images',)
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
STATIC_DIR = os.path.join(BASE_DIR, 'static',)
STATICFILES_DIRS = [STATIC_DIR]