def upload_file(file):
if file is not None:
import os
dir_path = settings.MEDIA_ROOT
(filename, extension) = os.path.splitext(file.name)
filename += '_' + uuid.uuid4().hex
filename += extension
if not os.path.exists(dir_path):
os.makedirs(dir_path)
file_path = os.path.join(dir_path, filename)
with open(file_path, 'wb') as f:
for chunk in file.chunks():
f.write(chunk)
return file_path
You should return the [media_url] (http s://docs.djangoproject.com/en/3.0/ref/settings/#media-url) instead of the [media_root] (http s://docs.djangoproject.com/en/3.0/ref/settings/#media-root).
I am not sure what your use case is - but you could look at [File_Field] (http s://docs.djangoproject.com/en/3.0/ref/models/fields/#filefield) which might provide the functionality that you might want to use. If its not quite what you want you can look at the [source] (http s://github.com/django/django/blob/f600e3fad6e92d9fe1ad8b351dc8446415f24345/django/db/models/fields/files.py) of the field and get an Idea how it is managed internally.
A good explanation on the broad topic would be [Managing Files] (http s://docs.djangoproject.com/en/3.0/topics/files/)
If all this didn’t help - please explain the thing that you are trying to accomplish a bit further, I might just didn’t catch it right.