34

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")
nik_m
  • 11,825
  • 4
  • 43
  • 57
Iftikhar Ali Ansari
  • 1,650
  • 1
  • 17
  • 27

3 Answers3

67
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/

Eduard Gamonal
  • 8,023
  • 5
  • 41
  • 46
edward
  • 2,455
  • 23
  • 12
  • 1
    I used this method trying to save a png, and got this error: `codecs.charmap_decode(input,self.errors,decoding_table)[0] odeError: 'charmap' codec can't decode byte 0x8f in position 207: char to ` Do you know how to fix this? – AllTradesJack Aug 01 '14 at 00:11
  • 4
    @AllTradesJack use 'rb' instead of 'r' flag, as Roy answered below – khue bui Aug 14 '17 at 04:55
33
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.

Gopal Roy
  • 879
  • 1
  • 8
  • 10
1

What worked for me was:

django.core.files.uploadedfile import UploadedFile
user1=User(name='abc')
user1.pic.save('abc.png', UploadedFile(file=open('/tmp/pic.png', 'rb'), content_type='image/png'))
Roy Martinez
  • 335
  • 5
  • 6