def attach_image_to_product(product, url): if not url: return url = url.replace(' ', '%20') img_temp = NamedTemporaryFile() img_temp.write(urllib2.urlopen(url).read()) img_temp.flush() pi = ProductImage() pi.name = product.title[:25] pi.product = product pi.image.save(product.title[:25], File(img_temp)) pi.save(using='default') product.has_images = True product.save(using='default')
def update(self, request, *args, **kwargs): product = Product.objects.get(pk=kwargs.get('pk')) serializer = AdminProductCreateSerializer(product, data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if 'preview' in request.FILES: preview = request.FILES['preview'] save_preview = ProductImage(image=preview, product_id=product.pk, is_preview=True) save_preview.save() if 'images' in request.FILES: for image in request.FILES.getlist('images'): image_to_save = ProductImage(image=image, product_id=product.pk, is_preview=False) image_to_save.save() return Response(serializer.data)
def create(self, request, *args, **kwargs): if request.data.get('parameters'): parameters = json.loads(request.data.get('parameters')) else: parameters = [] serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=False) self.perform_create(serializer) if len(parameters) > 0: print(parameters) parameters_to_db = [] for parameter in parameters: parameter_object = { 'name': parameter['name'], 'value': parameter['value'], 'product': serializer.data['id'] } parameters_to_db.append(parameter_object) param_ser = AdminParameterCreateSerializer(data=parameters_to_db, many=True) param_ser.is_valid(raise_exception=True) param_ser.save() if 'preview' in request.FILES: preview = request.FILES['preview'] save_preview = ProductImage(image=preview, product_id=serializer.data['id'], is_preview=True) save_preview.save() if 'images' in request.FILES: for image in request.FILES.getlist('images'): image_to_save = ProductImage(image=image, product_id=serializer.data['id'], is_preview=False) image_to_save.save() return Response(serializer.data)
def handle(self, *fixture_labels, **options): if len(fixture_labels) > 0: dirpath = fixture_labels[0] if not os.path.exists(dirpath): print 'Path does not exist:', dirpath return used = [] pictures = os.listdir(dirpath) products = [prod.slug for prod in Product.objects.active()] categories = [cat.slug for cat in Category.objects.active()] prod_folder = get_folder(PRODUCTS) cat_folder = get_folder(CATEGORIES) user = User.objects.get(is_superuser=True) for filename in pictures: base, _ = os.path.splitext(filename) if base in categories: image = save_image(cat_folder, dirpath, filename, user) cat = Category.objects.get(slug=base) if CategoryImage.objects.filter(category=cat, image=image, sort=0).count(): ci = CategoryImage.objects.get(category=cat, image=image) ci.image = image ci.save(force_update=True) else: ci = CategoryImage(category=cat, image=image) try: ci.save(force_insert=True) except IntegrityError: print 'Category:', cat, 'Image:', image, 'ci:', ci used.append(filename) elif base in products: image = save_image(prod_folder, dirpath, filename, user) product = Product.objects.get(slug=base) if ProductImage.objects.filter(product=product, image=image, sort=0).count(): pi = ProductImage.objects.get(product=product, image=image) pi.image = image pi.save(force_update=True) else: pi = ProductImage(product=product, image=image) try: pi.save(force_insert=True) except IntegrityError: print 'Product:', product print 'Image:', image print 'pi:', pi used.append(filename) print len(pictures), 'pictures' #print len(products), 'products' print len(used), 'used' print 'Unused:', len(pictures) - len(used)
def handle(self, *args, **options): parser = ElementTree.XMLParser(encoding="utf-8") productinorder = ProductInOrder.objects.all() productinorder.delete() productinbasket = ProductInBasket.objects.all() productinbasket.delete() product = Product.objects.all() product.delete() category = Category.objects.all() category.delete() manufacturer = Manufacturer.objects.all() manufacturer.delete() trans = str.maketrans( "абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", "abvgdeejzijklmnoprstufhzcss_y_euaABVGDEEJZIJKLMNOPRSTUFHZCSS_Y_EUA" ) tree = ElementTree.parse("./ImportExport/import.xml", parser=parser) root = tree.getroot() #print(root) for element in root.iter( "{urn:1C.ru:commerceml_210}Группа"): #Наименование категории name = element[1].text category = Category(name=name, id1C=element[0].text, url=slugify(name.translate(trans))) category.save() for element in root.iter("{urn:1C.ru:commerceml_210}Свойство"): #print(element[1].text) for elem in element.iter( "{urn:1C.ru:commerceml_210}Справочник"): #Бренд name = elem[1].text manufact = Manufacturer(name=name, id1C=elem[0].text, slug=slugify(name.translate(trans))) manufact.save() for element in root.iter("{urn:1C.ru:commerceml_210}Товар"): name = element.find("{urn:1C.ru:commerceml_210}Наименование").text category = element.find("{urn:1C.ru:commerceml_210}Группы") category_id = Category.objects.get(id1C=category[0].text) brend = element.find("{urn:1C.ru:commerceml_210}ЗначенияСвойств") if brend is not None: brend_id = Manufacturer.objects.get(id1C=brend[0][1].text) short_description = element.find( "{urn:1C.ru:commerceml_210}Описание").text country = element.find("{urn:1C.ru:commerceml_210}Страна") if country is None: country_text = "" else: country_text = country.text weight = element.find("{urn:1C.ru:commerceml_210}Вес") weight_float = 0 height = 0 width = 0 length = 0 if weight is not None: weight_float = Decimal(weight.text) for val_req in element.iter( "{urn:1C.ru:commerceml_210}ЗначениеРеквизита"): if val_req[0].text == 'Высота': height = Decimal(val_req[1].text) elif val_req[0].text == 'Ширина': width = Decimal(val_req[1].text) elif val_req[0].text == 'Длина': length = Decimal(val_req[1].text) #print(name, int(category_id.id), category_id.name, int(brend_id.id), brend_id.name) product = Product(name=name, id1C=element[0].text, category=category_id, short_description=short_description, country=country_text, weight=weight_float, height=height, width=width, length=length, manufacturer=brend_id, url=slugify(name.translate(trans))) product.save() #print(element[0].text) #print(name) img = 1 is_main = True if element.find("{urn:1C.ru:commerceml_210}Картинка") is not None: for elem in element.iter("{urn:1C.ru:commerceml_210}Картинка"): if elem is not None: #product=Product.objects.get(id1C=element[0].text) name_file = slugify( product.name.translate(trans)) + str(img) + ".jpg" shutil.copy("./ImportExport/" + elem.text, "./product_images/" + name_file) if img != 1: is_main = False prod_img = ProductImage(product=product, image="product_images/" + name_file, is_main=is_main) prod_img.save() img = img + 1 else: prod_img = ProductImage(product=product, image="product_images/no_image.png", is_main=is_main) prod_img.save() tree = ElementTree.parse("./ImportExport/offers.xml") root = tree.getroot() for element in root.iter("{urn:1C.ru:commerceml_210}Предложение"): #rest_float=0 product = Product.objects.get(id1C=element[0].text) for elem in element.iter("{urn:1C.ru:commerceml_210}Цена"): price = elem.find("{urn:1C.ru:commerceml_210}ЦенаЗаЕдиницу") if price is not None: product.price = Decimal(price.text) rest = element.find("{urn:1C.ru:commerceml_210}Количество") if rest is not None: product.rest = Decimal(rest.text) product.save()
try: feedutils.attach_image_to_product(product,url) except Exception, e: log.exception( 'Error adding image to product %s from %s: %s' % ( product.id, data['cleaned_data']['image_url'], repr(e))) else: # Dont download images, we will serve them using their original urls for url in data['cleaned_data']['image_url']: pi = ProductImage(product=product, type='external') if 'scene7' in url: pi.type = 'scene7' pi.name = product.title[:25] pi.url = url pi.save(using='default') if sync and not is_update: sync.new_masters += 1 sync.save(using='default') #sync_product = SyncEventProductMapping(sync_event=sync, # product=product, action='added') #sync_product.sku = data['cleaned_data']['sku'] #sync_product.save(using='default') if sync and is_update: sync.edits += 1 sync.save(using='default') #sync_product = SyncEventProductMapping(sync_event=sync, # product=product, action='edited') #sync_product.sku = data['cleaned_data']['sku']