Best way at add date time stamp in directory of django image field
Till now i was using this function
def user_compressed_path(instance, filename):
profile_pic_name = 'user/{0}/compressed/profile.jpg'.format(instance.id)
full_path = os.path.join(settings.MEDIA_ROOT, profile_pic_name)
if os.path.exists(full_path):
os.remove(full_path)
return profile_pic_name
def user_picture_path(instance, filename):
profile_pic_name = 'user/{0}/picture/profile.jpg'.format(instance.id)
full_path = os.path.join(settings.MEDIA_ROOT, profile_pic_name)
if os.path.exists(full_path):
os.remove(full_path)
return profile_pic_name
i want path something like
'user/{0}/compressed/{1}/profile.jpg'.format(instance.id, date_time_stamp)
'user/{0}/picture/{1}/profile.jpg'.format(instance.id, date_time_stamp)
what should be the value of date_time_stamp
You can do something like this
import datetime
date = datetime.datetime.now().date()
time = datetime.datetime.now().time()
def user_compressed_path(instance, filename):
profile_pic_name = f'user/{instance.id}/{date}/{time.strftime("%H:%M:%S")}/profile.jpg'
full_path = os.path.join(settings.MEDIA_ROOT, profile_pic_name)
if os.path.exists(full_path):
os.remove(full_path)
return profile_pic_name
this will return output like this assuming if instance have id 2
user/2/2021-12-12/10:45:09/profile.jpg