Django files tutorial - a1k89/Blog GitHub Wiki
How to save file manually from any source to FileField
I worked many times with incoming files from user.
- User send one or many files used by rest api (multipart/form-data)
- User send form with files
- Get image from remote URL, download and save to ImageField
Finally, I wrote this short tutorial.
- If you send files used by API/Form (multipart/form-data): request.FILES content your files
- Django has
FILE_UPLOAD_HANDLERSin settings.py:
[
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
]
- Together MemoryFileUploadHandler and TemporaryFileUploadHandler provide Django’s default file upload behavior of reading small files into memory and large ones onto disk.
- By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold the entire contents of the upload in memory.
- When you got a file, check it extension (for example, you want only png/jpeg)
- Finally, if all ok, you may to save file in
DjangoModelWithFileField. You may simple sendUploadedFiletoFileFieldand runsave
# files - list of UploadedFile
for file in files:
CommentFile.objects.create(comment=comment, file=file)
And that's it! Django save you MemoryFileUploadHandler or TemporaryFileUploadHandler to you real file with upload_to path.
- In a case with get image/file from remote URL:
from django.core.files.temp import NamedTemporaryFile
from django.core.files import File
from requests import get
request = get("https://cdn.shopify.com/s/files/1/0287/6846/9067/files/Michael-Kors-ad-campaign-the-impression-001-1-770x513_750x513_crop_center.jpg?v=1632498240")
tmp_file = NamedTemporaryFile(delete=True) # Create tmp file
tmp_file.write(request.content) # Write content to tmp_file
tmp_file.flush()
real_file = File(tmp_file, name='hello.jpg') # Create Django-like file with name
DjangoModelWithFileField.objects.create(file=real_file) # Save