是否有任何方法可以将从外部 url(在我的例子中是一个 excel 文件)获取的二进制数据保存到 Django FileField 中,并根据 django 项目设置将文件上传到目标?
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?
感谢您的帮助。如果我的案例需要更多信息,也请告诉我。
最佳答案
您可以使用django.core.files.uploadedfile.SimpleUploadedFile
将您的内容保存为模型实例的文件字段。
>>> 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()
关于python - 将从 url 获取的二进制数据保存到 Django FileField 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31444923/