Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving image/file through django shell

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

Everything 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")
like image 638
Iftikhar Ali Ansari Avatar asked Aug 31 '25 04:08

Iftikhar Ali Ansari


1 Answers

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/

like image 86
edward Avatar answered Sep 02 '25 17:09

edward