Can you upload to a subfolder using FileField?

2
When I set a FileField (or ImageField ), I have to specify a upload_to :

campo1 = models.FileField(upload_to="uploads")
campo2 = models.ImageField(upload_to="img/%Y/%m/%d")

In the first case, all files go to the "uploads" folder. In the second, they go to a different folder according to the year / month / day the upload occurred. In both cases, the folder is predefined.

I would like to upload to a subfolder of the one specified in upload_to . For example:

subpasta = request.POST("subpasta") # Ex.: foo/bar
arq = request.FILEs("arquivo")      # Ex.: baz.txt

meuModelo.campo1 = ... # Resultado esperado: MEDIA_ROOT/uploads/foo/bar/baz.txt

Is it possible to do this with FileField of Django? Or - even if you can not save the file in this way - alternatively get a file that is already in a subfolder of upload_to and simply make the template "point" to him?

    
asked by anonymous 24.07.2015 / 20:51

2 answers

1

Using a function in upload_to you can change the path / file reference, eg:

def upload_path_handler(instance, filename):
    return "uploads/%s/%s" % (instance.subpasta, filename)

class Arquivo(models.Model):
    arquivo = models.FileField(upload_to=upload_path_handler)

Reference: link

    
27.07.2015 / 15:55
1

The most incredible of upload_to is that you can define a function inside it, and with this function validate or do what you want. Helping you like this, what you need. In this example, I'm renaming the image:

class MyModel(models.Model):
    file = models.ImageField(upload_to=rename_upload_image)

def rename_upload_image(instance, filename):
        ext = filename.split('.')[-1]
        filename = "%s.%s" % (uuid.uuid4(), ext)
        return os.path.join('images/', filename)

I hope it helps you

    
27.07.2015 / 15:24