2

Is there any ways to save a binary data get from an external url (in my case, an excel file) into a Django FileField, with the file uploaded to the destination according to the django project settings?

class FileData(models.Model):
    excel_file = models.FileField(upload_to='excel_file_path')


import requests
url = 'https://www.example.getfile.com/file_id=234'
r = requests.get(url)
# How to store the binary data response to FileField?

Thanks for help. Please also let me know if further information is needed in my case.

1 Answer 1

5

You can make use of django.core.files.uploadedfile.SimpleUploadedFile to save your content as a file field of your model instance.

>>> import requests
>>> from django.core.files.uploadedfile import SimpleUploadedFile

>>> response = requests.get("https://www.example.getfile.com/file_id=234")

>>> excel_file = SimpleUploadedFile("excel.xls", response.content, content_type="application/vnd.ms-excel")
>>> file_data = FileData(excel_file=excel_file)
>>> file_data.save()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.