Save django images programmatically

Django January 08, 2021 python

Save django images programmatically

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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'))