2

Since some image files have name conflicts, I decided to make the system to change a uploaded file's name automatically. However, after changing the system, I got in trouble with getting a current date for the file path.

This is how my previous Image model looks like, and it stores an image with a name like boutique/index/2018/9/20/FILE_NAME.jpg.

class Image(TimeStampedModel):
    ...
    image = ImageField(..., upload_to='boutique/index/index/%Y/%m/%d')
    ...

After that, I changed it to like this. This successfully changes a uploaded image's name automatically. However, it stores a name like boutique/%Y/%m/%d/FILE_NAME.jpg.

def image_path(instance, filename):
    basefilename, file_extension = os.path.splitext(filename)
    chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
    randomstr = ''.join((random.choice(chars)) for x in range(10))
    return 'boutique/index/%Y/%m/%d/{imageid}/{basename}{randomstring}{ext}'.format(imageid=instance.store.domainKey, basename=basefilename, randomstring=randomstr, ext=file_extension)

class Image(TimeStampedModel):
    ...
    image = ImageField(..., upload_to=image_path)
    ...

Like you see the above, the problem is that %Y, %m, and %d don't provide date data I need anymore. What is wrong here? image_path function returns the same thing in the same place. I don't know why they are just like recognized as a normal string

1
  • You can use epoch time or combination of epoch time and user id to avoid name conflicts. Or is there any specific reason to use this pattern. Commented Sep 20, 2018 at 20:06

1 Answer 1

3

You have to set those values manually.

Add the import

from datetime import datetime

And replace in your function %Y, %m, %d with {year}, {month}, {day} variables and add the values to the format call.

def image_path(instance, filename):
    basefilename, file_extension = os.path.splitext(filename)
    chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
    randomstr = ''.join((random.choice(chars)) for x in range(10))
    _now = datetime.now()

    return 'boutique/index/{year}/{month}/{day}/{imageid}/{basename}{randomstring}{ext}'.format(
        imageid=instance.store.domainKey, 
        basename=basefilename, randomstring=randomstr, ext=file_extension,
        year=_now.strftime('%Y'), month=_now.strftime('%m'), day=_now.strftime('%d')
        )

More about file uploads in django

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.