def create(self, validated_data): supplier_id = validated_data['supplier_id'] category_id = validated_data['category_id'] Unit = validated_data['Unit'] ProductName = validated_data['ProductName'] Price = validated_data['Price'] try: category = Category.objects.get(pk=category_id) except Category.DoesNotExist: raise serializers.ValidationError( 'Category does not exist, please enter correct customer id') try: supplier = Supplier.objects.get(pk=supplier_id) except Supplier.DoesNotExist: raise serializers.ValidationError( 'Supplier does not exist, please enter correct customer id') product = Product(category=category, supplier=supplier, Unit=Unit, ProductName=ProductName, Price=Price) product.save() return product
def add_product(request): context = {} if request.method == "POST": product = Product(name=request.POST['name'], type=int(request.POST['type']), quantity=request.POST['stock'], description=request.POST['desc'], price=float(request.POST['price']), picture=request.FILES['picture']) product.save() context['add_log'] = "Product has been created" return render(request, 'add_product.html', context)
def InsertProduct(request): if request.method == 'POST': productname = request.POST.get('productname') productprice = request.POST.get('price') p = Product( name = productname, price = productprice, ownername = request.session['user'], owner = request.session['uid'], ) p.save() return HttpResponseRedirect("../")
def handle(self, *args, **kwargs): to_import_file = Path('.') / 'Product' / 'to_import.json' path_to_image_folder = Path('.') / 'Product' / 'test_pictures' if not path_to_image_folder.exists(): self.stdout.write('Download pictures...') download_test_pictures() self.stdout.write('Done!') with to_import_file.open() as f: to_import = json.load(f) # for prod_type in to_import['product_type']: # ProductType.objects.create(name=prod_type) ProductType.objects.bulk_create( ProductType(name=prod_type) for prod_type in to_import['product_type']) self.stdout.write('Created product types.') # for prod_trend in to_import['product_trend']: # ProductTrend.objects.create(name=prod_trend) ProductTrend.objects.bulk_create( ProductTrend(name=prod_trend) for prod_trend in to_import['product_trend']) self.stdout.write('Created product trends.') # for prod_style in to_import['product_style']: # ProductStyle.objects.create(name=prod_style) ProductStyle.objects.bulk_create( ProductStyle(name=prod_style) for prod_style in to_import['product_style']) self.stdout.write('Created product styles.') def _get_image(object_name, filename): path_to_image = path_to_image_folder / filename with path_to_image.open('rb') as f: image = Image.objects.create( name=object_name, value=File(f), ) return image Product.objects.bulk_create( Product( name=product['name'], image=_get_image(object_name=product['image'], filename=product['image']['value']), description=product['description'], product_type=ProductType.objects.get( name=product['product_type']), style=ProductStyle.objects.get(name=product['style']), trend=ProductTrend.objects.get(name=product['trend']), color=product['color'], cost=product['cost'], ) for product in to_import['products']) # for product in to_import['products']: self.stdout.write('Products created!')
def create(request): if request.method == "POST": Product1 = Product() Product1.name = request.POST.get("name") Product1.price = request.POST.get("price") Product1.Description = request.POST.get("Description") Product1.save() return HttpResponseRedirect("/")
def upload_product(request): if request.method == 'POST': shop = request.POST.get('shop') title = request.POST.get('title') img = request.FILES.get('img') price = request.POST.get('price') band = request.POST.get('band') description = request.POST.get('description') current_user = request.user alldata = Product(shop=shop, title=title, img=img, price=price, band=band, description=description) alldata.user_id = current_user.id if img: alldata.save() return redirect('shop') else: return redirect('upload') return render(request, 'upload.html')
def create(request): if request.method == "POST": product = Product() product.name = request.POST.get("name") product.price = request.POST.get("price") product.Description = request.POST.get("Description") if product.name == '': return HttpResponseNotFound("<h2>Не все поля заполнены!!!</h2>") elif product.price == '': return HttpResponseNotFound("<h2>Не все поля заполнены!!!</h2>") elif product.Description == '': return HttpResponseNotFound("<h2>Не все поля заполнены!!!</h2>") else: product.save() return HttpResponseRedirect("/") else: return render(request, "../templates/Product/create.html")
name=locationName + str(i), phone='0xxxxxxxxx', address=str(locationName + str(i)) + ' street, City, Country', email=str(locationName + str(i)) + '@domain.com') location.save() locationsIDs.append(location) print "Done adding Location" productCategory = ProductCategory(name='TV') productCategory.save() products = [ 'Samsung UA40J5200AK', 'LG 49LH590V', 'Samsung UA40J5000', 'LG 42LF550T' ] for productName in products: product = Product(fk_category=productCategory, name=productName) product.save() productsIDs.append(product) productCategory = ProductCategory(name='Laptop') productCategory.save() products = ['Apple Pro', 'Dell N5110', 'Lenovo z5170', 'ASUS Transformer'] for productName in products: product = Product(fk_category=productCategory, name=productName) product.save() productsIDs.append(product) productCategory = ProductCategory(name='Mobiles') products = ['iPhone', 'sony z5', 'Samsung Note 6', 'ASUS Zenfone selfie'] productCategory.save() for productName in products:
def run(): data_dir = os.path.join(settings.BASE_DIR, 'data\STock.xls') book = xlrd.open_workbook(data_dir) sheet = book.sheet_by_index(0) data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(6, sheet.nrows)] # print(data) for item in data: product = Product() product.code = item[0] product.name = item[1] product.unit = item[2] product.stock = item[3] product.cost_price = item[8] product.m_r_p = item[9] product.purchase_price = item[10] product.sales_price = item[11] product.company = item[12] product.save()
def create_new_item(data: dict) -> JsonResponse: """Добавляет Продукт в БД""" try: new_item = Product.objects.get(product_vendor_code=data['vendor_code']) print('Обновление продукта... id=' + str(new_item.id)) except ObjectDoesNotExist: new_item = Product() print('Создание нового продукта...') new_item.product_category = ProductCategory.objects.get( category_title=data['category']) new_item.product_vendor = ProductVendor.objects.get(id=11) new_item.product_vendor_code = data['vendor_code'] new_item.product_title = data['title'] new_item.product_url = data['url'] new_item.product_extra_desc = data['short_description'] new_item.product_count = data['count'] new_item.product_img_title = data['title'].split(',')[0] if data['price_type'] == 1: print('Простая цена') new_item.product_price_choice = data['price_type'] new_item.product_price = data['price'] elif data['price_type'] == 2: print('Цена с опциями') new_item.product_price_choice = data['price_type'] new_item.product_price = 0 try: new_option_group = OptionGroup.objects.get( option_group=data['title'].split(',')[0]) print('Редактируем группу опций id=' + str(new_option_group.id)) except ObjectDoesNotExist: new_option_group = OptionGroup() print('Создаем новую группу опций...') new_option_group.option_group = data['title'].split(',')[0] new_option_group.product_price_option = 'Длина рулона' new_option_group.save() print('Группа опций готова') # print(data['price_options']) print('Созадем опции') print('\t5.5 м', end=' ') try: new_option_price_5 = ProductOptionPrice.objects.filter( product_option_group=new_option_group).get( product_option=OptionPrice.objects.get(id=49)) print('- Редактируем опцию id=' + str(new_option_price_5.id)) except ObjectDoesNotExist: print('- Создаем новую опцию') new_option_price_5 = ProductOptionPrice() new_option_price_5.product_option_group = new_option_group new_option_price_5.product_option = OptionPrice.objects.get(id=49) new_option_price_5.product_option_price = data['price_options']['5'] new_option_price_5.save() print('\t5.5 м - СОХРАНЕНО') print('\t10 м', end=' ') try: new_option_price_10 = ProductOptionPrice.objects.filter( product_option_group=new_option_group).get( product_option=OptionPrice.objects.get(id=48)) print('- Редактируем опцию id=' + str(new_option_price_10.id)) except ObjectDoesNotExist: print('- Создаем новую опцию') new_option_price_10 = ProductOptionPrice() new_option_price_10.product_option_group = new_option_group new_option_price_10.product_option = OptionPrice.objects.get(id=48) new_option_price_10.product_option_price = data['price_options']['10'] new_option_price_10.save() print('\t10 м - СОХРАНЕНО') # img # FIXME: Добавить проверку что такое изображение уже есть # if data['img'].split('/')[-1] in ... # print('Такое изображение уже есть') print('Загружаем Изображение', end='\r') from PIL import Image import requests response = requests.get(data['img'], stream=True) response.raw.decode_content = True img = Image.open(response.raw) from io import BytesIO from django.core.files import File blob = BytesIO() if data['img'].split('.')[-1] == 'jpg': format = 'JPEG' else: format = 'JPEG' img.save(blob, format) new_item.product_img.save(data['img'].split('/')[-1], File(blob), save=False) print('Изображение загружено') attrs = dict(data['attrs']) product_tab = ProductTab.objects.get(id=22) #Cosca Обои Преимущества new_tabs = [] for attr_title, attr_value in attrs.items(): if 'материал' in attr_title.lower(): if 'бамбук' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=23)) if 'джут' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=24)) if 'тростник' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=25)) if 'сизал' in attr_value.lower( ) and 'бархат' not in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=26)) if 'златоцвет' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=27)) if 'сизал' in attr_value.lower() and 'бархат' in attr_value.lower( ): new_tabs.append(ProductTab.objects.get(id=28)) if 'ситник' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=29)) if 'крапив' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=30)) if 'лен' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=31)) if 'магноли' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=32)) if 'вьюн' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=33)) if 'будд' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=34)) if 'слюда' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=35)) if 'шпон' in attr_value.lower() and 'пробк' in attr_value.lower( ) and 'дуб' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=36)) if 'шпон' in attr_value.lower() and 'абак' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=37)) if 'шпон' in attr_value.lower() and 'шанхай' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=38)) if 'велюр' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=39)) if 'хлоп' in attr_value.lower() and 'ткань' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=40)) if 'цел' in attr_value.lower() and 'волокно' in attr_value.lower( ) and 'тканая' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=41)) if 'бумага' in attr_value.lower( ) and 'нетканая' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=42)) if 'папирус' in attr_value.lower(): new_tabs.append(ProductTab.objects.get(id=43)) print(f'Вкладки: {new_tabs}') # elif new_item.product_category.id == 88: # Обои из бамбука # tab_from_category = ProductTab.objects.get(id=25) # Cosca Обои Тростник Описание print('Данные обработаны') try: print('Проверка...', end='\r') new_item.full_clean() print('Проверка прошла успешно') print('Сохраняем...', end='\r') new_item.save() print('СОХРАНЕНО') # атрибуты print('Созадем атрибуты') for attr_title, attr_value in attrs.items(): try: new_attr = ProductAttribute.objects.filter( attribute_product_id=new_item.id).get( attribute_title=attr_title) print('\tРедактируем атрибут id=' + str(new_attr.id)) except ObjectDoesNotExist: print('\tСоздаем новый атрибут') new_attr = ProductAttribute() new_attr.attribute_product = new_item new_attr.attribute_title = attr_title new_attr.attribute_value = attr_value new_attr.save() # print('\tАтрибут - СОХРАНЕН') new_item.product_tab.add(product_tab) for tab in new_tabs: # if len(new_tabs) > 0: new_item.product_tab.add(tab) if data['price_type'] == 2: new_item.product_price_options.add(new_option_group) return JsonResponse(data={ 'id': new_item.id, 'url': new_item.product_category.category_url + '/' + new_item.product_url + '/' }, status=200) except ValidationError as e: print('Проверка провалилась!') return JsonResponse(e.message_dict, safe=False, status=500)
def product_instances(): product1 = Product() product2 = Product() yield (product1, product2) del product1 del product2