Save Upload File To Dynamic Directory And Get The Path For Store In Db
I'm uploading a file and additionally some data like file's id and file's title to the server. I have the view below to handle the request and I want to save the file to a dynamic
Solution 1:
You put the cart before the horse. Start from the beginning, first things first. And the first thing is the user story, then the model layer.
There are Products and a Product can have many ProductVideos. A Product has an Author (the Author can have many Products). When you upload a ProductVideo for a particular Product, you want to save it in a directory which contains the Author ID.
Therefore we specify a callable for the FileField which should dynamically find out the id of the Author:
defuser_directory_path(instance, filename):
# get the id of the author# first get the Product, then get its author's id
user_id = str(instance.p_id.author.id)
# little bit cosmetics# should the filename be in uppercase
filename = filename.lower()
return'user_{0}/{1}'.format(user_id, filename)
When saving an instance of Product_Video the uploaded file should be stored in a directory with a dynamically created pathname based on the author's ID.
Further I'd suggest you to follow established coding conventions:
- don't use
snake_casefor class names, especially don't mix it with capital letters. UsePascalCase, preferably singular nouns, for class names:ProductVideo - if your model class is
ProductVideo, keep that name in all subsequent classes:ProductVideoSerializerfor the model serializer andProductVideoAPIViewfor the generic view. - use verbs for methods and standalone functions,
get_user_directoryorupload_to_custom_pathis better thanuser_directory_path. - also avoid suffixing the foreign key fields with
_id. Use ratherproductinstead ofp_id. Django will allow you to access the related object by callingproductand get the id of the object by callingproduct_id. Using the namep_idmeans you'll access the id of the related object by callingp_id_idwhich looks very weird and confusing.
Post a Comment for "Save Upload File To Dynamic Directory And Get The Path For Store In Db"