63๐
Using default_storage
is better than FileSystemStorage
.
You can save file to MEDIA_ROOT
with FileSystemStorage
but when you change DEFAULT_FILE_STORAGE
backend in the future this may not work anymore.
If you use default_storage
, in the future if you want to use aws, azure etc as file store with multiple Django worker your code will work without any change.
default_storage usage example:
from django.core.files.storage import default_storage
# Saving POST'ed file to storage
file = request.FILES['myfile']
file_name = default_storage.save(file.name, file)
# Reading file from storage
file = default_storage.open(file_name)
file_url = default_storage.url(file_name)
24๐
you can upload files to django server : :
from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage
def upload(request):
folder='my_folder/'
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage(location=folder) #defaults to MEDIA_ROOT
filename = fs.save(myfile.name, myfile)
file_url = fs.url(filename)
return render(request, 'upload.html', {
'file_url': file_url
})
else:
return render(request, 'upload.html')
- [Django]-How to set and get cookies in Django?
- [Django]-Embed YouTube video โ Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'
- [Django]-Backwards migration with Django South
12๐
You can use django FileField
, it support specify a upload_to
parameter, like this:
data_file = models.FileField(upload_to=content_path)
Where content_path
can be a string or a function which returns a string.
- [Django]-How to get primary keys of objects created using django bulk_create
- [Django]-Django filter many-to-many with contains
- [Django]-How to remove all of the data in a table using Django
2๐
Use the following code to update a FileField
or ImageField
. Django will upload the file to settings.MEDIA_ROOT
per default.
from os.path import basename
from django.core.files import File
self.model.file_field.save(basename(path), content=File(open(path, 'rb')))
Afterwords you can access:
The path like this:
self.model.file_field.path
The url like this:
self.model.file_field.url
- [Django]-How to query abstract-class-based objects in Django?
- [Django]-How to reverse the URL of a ViewSet's custom action in django restframework
- [Django]-How can i set the size of rows , columns in textField in Django Models