Save django images programmatically

Django -- Posted on Jan. 8, 2021

Save django images programmatically

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

Related Posts