[Answered ]-How can I upload two images in a form to 2 different directories in django?

1👍

models.py

def get_pic1_path(instance, filename):
    return new_path(path="pic1", filename)

def get_pic2_path(instance, filename):
    return new_path(path="pic2", filename)

def new_path(path, filename):
    today = date.now()
    today_path = today.strftime("%Y-%m-%d")
    image_path = "{0}-{1}".format(today_path, filename)
    return os.path.join(path, image_path)

class Model1(models.Model):
    ...
    pic1 = models.CustomImageField(upload_to=get_pic1_path)
    pic2 = models.ImageField(upload_to=get_pic2_path)

views.py

...
    if request.method == 'POST':
        form = Model1Form(request.POST, request.FILES)
        if form.is_valid():
            image = Model1.objects.create()
            pic1 = request.FILES['pic1']
            pic2 = request.FILES['pic2']

            image.pic1.save(pic1.name, image_file)
            image.pic2.save(pic2.name, image_file)
...

1👍

I think I must have misunderstood your question. Surely this does exactly what you’re describing –

class Model1(models.Model):
    ...
    pic1 = models.ImageField(upload_to="pic1")
    pic2 = models.ImageField(upload_to="pic2")

The file in the pic1 field will be uploaded to MEDIA_ROOT/pic1/ and the file in the pic2 field will be uploaded to MEDIA_ROOT/pic2/.

UPDATE

Have a look at the docs on the upload_to parameter – you can pass it a function to create the path dynamically, as described in Catherines answer.

I know it’s not quite what you’re planning, but if you wanted something super simple to organise your files, then it’s worth noting that you can also use strftime notation in the upload_to parameter.

pic1 = models.ImageField(upload_to='pic1/%Y/%m/%d')

This would give you a path like – /path/to/media_root/pic1/2013/03/11/filename.jpg

Leave a comment