How to save image file through django shell

+1 vote

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

Any help!

Jun 29, 2020 in Python by kartik
• 37,510 points
3,941 views

1 answer to this question.

0 votes

Hii @kartik,

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

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

In this case, the user1.pic.save method will also save the user1 instance. 

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

Hope it helps!!

Thank you!!

answered Jun 29, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How to save Numpy array as image in python?

If you have matplotlib, you can do: import ...READ MORE

answered Nov 16, 2018 in Python by Nymeria
• 3,560 points
8,557 views
0 votes
1 answer

How do you configure Django to send mail through Postfix?

You can do this by adding  settings.py ...READ MORE

answered Feb 25, 2019 in Python by SDeb
• 13,300 points
4,544 views
+1 vote
1 answer
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
2,044 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
1,191 views
+1 vote
1 answer

How to create a file and save it to a model's FileField in Django?

Hello @kartik, Basically, a field declared as a FileField, ...READ MORE

answered Jun 30, 2020 in Python by Niroj
• 82,880 points
14,023 views
0 votes
1 answer

How to load a custom JS file in Django admin home?

Hello @kartik, You can override templates/admin/index.html and add the JavaScript ...READ MORE

answered May 14, 2020 in Python by Niroj
• 82,880 points
7,237 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP