I am trying to save an image file through django shell.
我试图通过django shell保存图像文件。
My model.py
is:
我的model.py是:
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:
使用admin和表单可以很好地使用Everyhing但是我想使用shell保存图像:
something like
就像是
>>>user1=User(name='abc', pic="what to write here")
2 个解决方案
#1
39
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
.
最终将图像abc.png复制到ImageField中指定的upload_to目录中。
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/
在这种情况下,user1.pic.save方法也将保存user1实例。保存ImageField的文档可以在这里找到https://docs.djangoproject.com/en/dev/ref/files/file/
#2
11
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.
请使用'rb'而不是'r'。如果您使用的是python3。
#1
39
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
.
最终将图像abc.png复制到ImageField中指定的upload_to目录中。
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/
在这种情况下,user1.pic.save方法也将保存user1实例。保存ImageField的文档可以在这里找到https://docs.djangoproject.com/en/dev/ref/files/file/
#2
11
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.
请使用'rb'而不是'r'。如果您使用的是python3。