Can I upload to a subfolder using Filefield?

Asked

Viewed 557 times

2

When I define one FileField (or ImageField), I need 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 "uploads" folder. In the second, they go to a different folder according to the year/month/day the upload took place. In both cases, the folder is default.

I would like however 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

It is possible to do this with the FileField do Django? Or - even if you can’t salvage the file this way - alternatively take a file that is already in a sub-folder of upload_to and simply make the model "point" at him?

2 answers

1

The most amazing thing about upload_to is that you can define a function within it, and with this function validate or do whatever you want. Helping you so, what you would need. In this example, I am 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

1


  • 1

    instance would be an instance of the model? At what point this method is called, is when the file is assigned, when the model is saved... An example of use and/or reference for documentation would help a lot if you have any. Ideally, I would like to do this without having to create a field subpasta in the model, only use an external parameter, as exemplified in the question. But if you can’t handle it, I’ll add an extra column and do it that way, do what...

  • instance is the instance of the model yes, with that you could save for example the files inside a directory with the id user’s. This example will only be included in the documentation in the next version of Django, it is already possible to see this link https://docs.djangoproject.com/en/dev/ref/models/fields/#Django.db.models.FileField.upload%5Fto

  • Regarding the subfolder you will have to create a column, because it will always access the name of this subfolder dynamically.

  • 1

    Thanks, it worked here (Django 1.4). Just one detail that is not explicit in the documentation: the returned path needs to be relative, i and.. can’t start with bar (ex.: /uploads/...). Otherwise, a SuspiciousFileOperation and thus a "Bad Request (400)". More information in that reply in Soen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.