categorylanri import qilish qoshildi

This commit is contained in:
Husanjonazamov
2026-03-26 14:06:37 +05:00
parent 00f9e6be54
commit bcea5f4a70
13 changed files with 319 additions and 56 deletions

View File

View File

@@ -0,0 +1,60 @@
import requests
from django.core.management.base import BaseCommand
from django.core.files.base import ContentFile
from core.apps.vendors.models import VendorproductModel, CategoryModel, VendorModel
import os
class Command(BaseCommand):
help = 'Syncs images from photo_url/photos_json to ImageField if they are empty'
def handle(self, *args, **options):
self.sync_categories()
self.sync_vendors()
self.sync_products()
def download_image(self, url):
if not url or not url.startswith('http'):
return None
try:
response = requests.get(url, timeout=10)
if response.status_code == 200:
name = os.path.basename(url.split('?')[0])
if not name:
name = "image.png"
return ContentFile(response.content, name=name)
except Exception as e:
self.stdout.write(self.style.ERROR(f"Error downloading {url}: {e}"))
return None
def sync_categories(self):
self.stdout.write("Syncing Category images...")
for obj in CategoryModel.objects.filter(photo__isnull=True).exclude(photo_url__isnull=True):
if not obj.photo_url.startswith('http'): continue
file_content = self.download_image(obj.photo_url)
if file_content:
obj.photo.save(file_content.name, file_content, save=True)
self.stdout.write(self.style.SUCCESS(f"Saved photo for category: {obj.title}"))
def sync_vendors(self):
self.stdout.write("Syncing Vendor images...")
for obj in VendorModel.objects.filter(photo__isnull=True).exclude(photo_url__isnull=True):
if not obj.photo_url.startswith('http'): continue
file_content = self.download_image(obj.photo_url)
if file_content:
obj.photo.save(file_content.name, file_content, save=True)
self.stdout.write(self.style.SUCCESS(f"Saved photo for vendor: {obj.title}"))
def sync_products(self):
self.stdout.write("Syncing Product images...")
for obj in VendorproductModel.objects.filter(image__isnull=True).exclude(photos_json__isnull=True):
if not isinstance(obj.photos_json, list) or len(obj.photos_json) == 0:
continue
url = obj.photos_json[0]
if not isinstance(url, str) or not url.startswith('http'):
continue
file_content = self.download_image(url)
if file_content:
obj.image.save(file_content.name, file_content, save=True)
self.stdout.write(self.style.SUCCESS(f"Saved image for product: {obj.name}"))