1

I'm Currently developing a app with a ManyToMany ImageField Relantionship . I want to have the ImageField save all images to a specific folder based on the ID of the Relantionship.

I want to have something like this.

class PostImages(models.Model):

image = models.ImageField(upload_to='Post_Images/post/' + post.id)

class Post(models.Model):

images = models.ManyToManyField(PostImages)

How do I access the post.id to do this ? I mostly want to do this for organization purposes right now cause its on my local machine but also see no reason to change it when I deploy.

  • You could have a look to a related question already ask: https://stackoverflow.com/questions/50591304/django-dynamic-filefield-upload-to – Leeuwtje Jul 06 '21 at 09:17

1 Answers1

0

E.g. based on FileField^ but the same you can use for ImageField:

def get_file_path(instance, filename):
    return instance.created.strftime("folder/%Y/%m/%d/") + instance.post.id

bfile = models.FileField(upload_to=get_file_path, null=True)