D
D
Dauren S2016-02-28 08:13:10
Django
Dauren S, 2016-02-28 08:13:10

Django loading image in folder by post id?

In the admin panel, I created a field for uploading an image. everything loads fine, but I want the images to be loaded into a folder that would be generated by the post id.
That is, I create a new entry in the admin panel, a folder with the id of this entry is created and pictures are saved there

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2016-02-28
@deliro

You can override the upload_to field of ImageField (as well as FileField) and give it a function that takes two arguments - a model object and a file name. You will end up with something like this:

import os
from django.conf import settings
def get_image_path(instance, filename):
    # Но так никогда нельзя делать!
    return os.path.join('images', str(instance.pk), filename)

And this would be better:
import os
from uuid import uuid1
def get_image_path(instance, filename):
    result = os.path.join('images', str(instance.pk), uuid1().hex)
    if '.' in filename:
        result = os.path.join(result, filename.split('.')[-1])
    return result

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question