mike
mike

Reputation: 1

django custom file storage path

i would like to dynamically set the file storage path from the view regardless of the actual media_root path. is this possible. i have looked into custom storage objects and i am aware of the custom upload_to method call. currently i have a method that is called when my ImageField model upload_to is specified. this lets me change the directory within media_root. i have tried to do something similar with an overriden FileSystemStorage class but whatever it is set to i think it is bound before i can modify it within a view. if fileupload handler is the way to go i would be curious as to how to implement one.

Upvotes: 0

Views: 2749

Answers (2)

Aamir Rind
Aamir Rind

Reputation: 39719

you can do this in your view path = default_storage.save(filePath, ContentFile(file)) where filePath is file path where you need to store, and file is the file which is uploaded by user. this function will return you the path by storing file.

file = request.FILES['filee']
filePath = '%s/%s' % ('path/to/directory', file.name)
file = file.read()
path = default_storage.save(filePath, ContentFile(file))

Upvotes: 1

Kirill
Kirill

Reputation: 3454

If path that you specified in upload_to starts with / then it will be considered as absolute path. Through this you can set any path that you want regardless of MEDIA_ROOT.

Upvotes: 1

Related Questions