отлично работает для новых записей:
def download_image_from_url(self, url, name):
# Stream the image from the url
try:
request = requests.get(url, stream=True)
except requests.exceptions.RequestException as e:
self.stderr.write(self.style.ERROR('Image request error: ' + str(e)))
return None
if request.status_code != requests.codes.ok:
self.stderr.write(self.style.ERROR('Error. Image request status code: ' + str(request.status_code)))
return None
# Create a temporary file
lf = tempfile.NamedTemporaryFile()
# Read the streamed image in sections
for block in request.iter_content(1024 * 8):
# If no more file then stop
if not block:
break
# Write image block to temporary file
lf.write(block)
return files.File(name=name + '.' + request.headers.get('content-type')[-3:], file=lf)
но при попытке сохранения (после удачного нового присваивания уже существующего поля картинки) - он падает с вот такой непонятной ошибкой:
Traceback (most recent call last):
File "D:/Projects/digrate.loc/manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Eugene\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line
utility.execute()
File "C:\Users\Eugene\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Eugene\Envs\venv\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Eugene\Envs\venv\lib\site-packages\django\core\management\base.py", line 330, in execute
output = self.handle(*args, **options)
File "D:\Projects\digrate.loc\ico\management\commands\coingecko.py", line 222, in handle
ico.save()
File "C:\Users\Eugene\Envs\venv\lib\site-packages\django\db\models\base.py", line 808, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\Eugene\Envs\venv\lib\site-packages\django\db\models\base.py", line 838, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\Eugene\Envs\venv\lib\site-packages\django\db\models\base.py", line 902, in _save_table
for f in non_pks]
File "C:\Users\Eugene\Envs\venv\lib\site-packages\django\db\models\base.py", line 902, in <listcomp>
for f in non_pks]
File "C:\Users\Eugene\Envs\venv\lib\site-packages\django\db\models\fields\files.py", line 294, in pre_save
if file and not file._committed:
AttributeError: 'tuple' object has no attribute '_committed'
ЧЯДНТ?
используй django.core.files.File
Обсуждают сегодня