from django.core.management.base import BaseCommand, CommandError from place_exposition.models import PlaceExposition from django.contrib.sites.models import Site from photologue.models import Gallery, Photo from file.models import FileModel from django.core.files import File from django.core.files.temp import NamedTemporaryFile import urllib2 from django.conf import settings #img_temp = NamedTemporaryFile(delete=True) #img_temp.write(urllib2.urlopen(url).read()) #img_temp.flush() #im.file.save(img_filename, File(img_temp)) def convert_photo(photo): domain = 'http://hit.expomap.ru' url = domain+photo.file_path.url file_name = url.split('/')[-1] download_to = settings.MEDIA_ROOT+'photologue/'+file_name try: response = urllib2.urlopen(url, timeout=5) except: print('download error') return None with open(download_to,'wb') as f: f.write(response.read()) f.close() file_name = 'photologue/'+file_name new_photo = Photo(image=file_name) new_photo.translate('en') new_photo.title = file_name.replace('photologue/', '') new_photo.save() return new_photo def handle_place(place): domain = 'http://hit.expomap.ru' for photo in list(place.photos.all()): new_photo = convert_photo(photo) place.upload_photo(new_photo) print(place) class Command(BaseCommand): def handle(self, *args, **options): for place in PlaceExposition.objects.all('en'): if place.photos.all().exists(): handle_place(place) """ url = 'adnec-abu-dhabi-national-exhibitions-center' p = PlaceExposition.objects.get(url=url) handle_place(p) """