Reputation: 256
So, I'm attempting to use request.get to pull an image from the web and save it to a django database. This is some code as follows and the steps that I have attempted:
My Model (just the needed bit, not all of it)
class Pistol(models.Model):
gun_id = models.CharField(max_length=255)
manufacturer = models.CharField(max_length=255, blank=True)
model = models.CharField(max_length=255, blank=True)
image = models.ImageField(upload_to='img/inventory', blank=True)
My Code (I'm doing this from a shell so it may seem unorganized slightly)
import request
r = requests.get('http://media.server.theshootingwarehouse.com/small/2451.jpg')
item = Pistol(gun_id="1", price=400, image="1.jpg")
item.image.save('1.jpg',r.content)
And then I get the following error
AttributeError: 'bytes' object has no attribute 'read'
Note I am working in python3
.
Upvotes: 6
Views: 2835
Reputation: 2439
For python3 i created a Management command i hope it can help you
import requests
from django.core.files.base import ContentFile
from django.core.management.base import BaseCommand, CommandError
from app.models import MyModel
class Command(BaseCommand):
help = 'save images to MyModel table'
def handle(self, *args, **options):
for model in MyModel.objects.all():
url = 'url_path_to_image'
r = requests.get(url)
if r.status_code == 200:
data = r.content
filename = url.split('/')[-1]
model.image.save(filename, ContentFile(data))
model.save()
print(model.pk)
self.stdout.write(self.style.SUCCESS('Successfully saved MyModel images'))
Upvotes: 3