Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将从url获取的二进制数据保存到Django文件字段_Python_Django_Python 2.7_Django 1.7 - Fatal编程技术网

Python 将从url获取的二进制数据保存到Django文件字段

Python 将从url获取的二进制数据保存到Django文件字段,python,django,python-2.7,django-1.7,Python,Django,Python 2.7,Django 1.7,有没有办法将从外部url(在我的例子中是excel文件)获取的二进制数据保存到Django文件字段中,并根据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.g

有没有办法将从外部url(在我的例子中是excel文件)获取的二进制数据保存到Django文件字段中,并根据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?
谢谢你的帮助。如果我的案例需要更多信息,请告知我。

您可以利用将内容保存为模型实例的文件字段

>>> 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()