Answer the question
In order to leave comments, you need to log in
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
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)
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 questionAsk a Question
731 491 924 answers to any question