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?
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 fieldsubpasta
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...– mgibsonbr
instance
is the instance of the model yes, with that you could save for example the files inside a directory with theid
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– Paulo
Regarding the subfolder you will have to create a column, because it will always access the name of this subfolder dynamically.
– Paulo
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, aSuspiciousFileOperation
and thus a "Bad Request (400)". More information in that reply in Soen.– mgibsonbr