Last active
August 25, 2021 00:36
-
-
Save LeoHeo/5131362006bd2ee9b693b3e29692c42f to your computer and use it in GitHub Desktop.
django ImageField custom function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import os | |
from django.db import models | |
def set_filename_format(now, instance, filename): | |
""" | |
file format setting | |
e.g) | |
{username}-{date}-{microsecond}{extension} | |
hjh-2016-07-12-158859.png | |
""" | |
return "{username}-{date}-{microsecond}{extension}".format( | |
username=instance.user.username, | |
date=str(now.date()), | |
microsecond=now.microsecond, | |
extension=os.path.splitext(filename)[1], | |
) | |
def user_directory_path(instance, filename): | |
""" | |
image upload directory setting | |
e.g) | |
images/{year}/{month}/{day}/{username}/{filename} | |
images/2016/7/12/hjh/hjh-2016-07-12-158859.png | |
""" | |
now = datetime.datetime.now() | |
path = "images/{year}/{month}/{day}/{username}/{filename}".format( | |
year=now.year, | |
month=now.month, | |
day=now.day, | |
username=instance.user.username, | |
filename=set_filename_format(now, instance, filename), | |
) | |
return path | |
class Experience(models.Model): | |
... | |
image = models.ImageField( | |
upload_to=user_directory_path, | |
) | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment