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.

  1. If you send files used by API/Form (multipart/form-data): request.FILES content your files
  2. Django has FILE_UPLOAD_HANDLERS in settings.py:
[
    'django.core.files.uploadhandler.MemoryFileUploadHandler',
    'django.core.files.uploadhandler.TemporaryFileUploadHandler',
]
  1. Together MemoryFileUploadHandler and TemporaryFileUploadHandler provide Django’s default file upload behavior of reading small files into memory and large ones onto disk.
  2. By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold the entire contents of the upload in memory.
  3. When you got a file, check it extension (for example, you want only png/jpeg)
  4. Finally, if all ok, you may to save file in DjangoModelWithFileField. You may simple send UploadedFile to FileField and run save
# 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.

  1. 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