from django.core.management.base import BaseCommand from establishment.models import Establishment, EstablishmentGallery from gallery.models import Image import requests from rest_framework import status class Command(BaseCommand): help = 'Fill establishment gallery from existing images' def handle(self, *args, **kwargs): count = 0 not_valid_link_counter = 0 not_valid_urls = [] cdn_prefix = 'https://1dc3f33f6d-3.optimicdn.com/gaultmillau.com/' establishments = Establishment.objects.exclude(image_url__isnull=True) \ .exclude(preview_image_url__isnull=True) for establishment in establishments: image_url = establishment.image_url.rstrip() relative_image_path = image_url[len(cdn_prefix):] #response = requests.head(image_url, allow_redirects=True) #if response.status_code != status.HTTP_200_OK: # not_valid_link_counter += 1 # not_valid_urls.append(image_url) image, image_created = Image.objects.get_or_create( orientation=Image.HORIZONTAL, title=f'{establishment.name} - {relative_image_path}', image=relative_image_path) gallery, _ = EstablishmentGallery.objects.get_or_create(establishment=establishment, image=image, is_main=True) if image_created: count += 1 self.stdout.write(self.style.WARNING(f'Created/updated {count} objects.\n' f'Not valid link counter: {not_valid_link_counter}\n' f'List of non valid image url: {not_valid_urls}'))