Saving image/file through django shell

跟風遠走 提交于 2019-11-30 11:24:40

问题


I am trying to save an image file through django shell.

My model.py is:

class user(models.Model):
    name=models.CharField(max_length=20)
    pic=models.ImageField()

Everyhing is fine with admin and forms but I want to save image using shell:

something like

>>>user1=User(name='abc', pic="what to write here")

回答1:


from django.core.files import File

user1=User(name='abc')
user1.pic.save('abc.png', File(open('/tmp/pic.png', 'r')))

You will end up with the image abc.png copied into the upload_to directory specified in the ImageField.

In this case, the user1.pic.save method will also save the user1 instance. The documentation for saving an ImageField can be found here https://docs.djangoproject.com/en/dev/ref/files/file/




回答2:


from django.core.files import File
user1=User(name='abc')
user1.pic.save('abc.png', File(open('/tmp/pic.png', 'rb')))

Please Use 'rb' instead of 'r'. If you are using python3.



来源:https://stackoverflow.com/questions/15332086/saving-image-file-through-django-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!