def test_thumbnail_are_generated_on_save(self): product = Product( name='The Cathedral and the bazaar', price=Decimal('10.00'), ) product.save() with open('main/fixtures/the-cathedral-the-bazaar.jpg', 'rb') as f: image = ProductImage( product=product, image=ImageFile(f, name='tctb.jpg'), ) with self.assertLogs('main', level='INFO') as cm: image.save() self.assertGreaterEqual(len(cm.output), 1) image.refresh_from_db() with open( 'main/fixtures/the-cathedral-the-bazaar.thumb.jpg', 'rb', ) as f: expected_content = f.read() self.assertEqual(expected_content, image.thumbnail.read()) image.thumbnail.delete(save=False) image.image.delete(save=False)
def setUp(self): ###### create Users ####### users = ['UserA', 'UserB', 'UserC', 'UserD'] for i in range(4): newUser = AUser(password='', last_login=timezone.now(), is_superuser=True, username=users[i], first_name='Firstname', last_name='Lastname', email='*****@*****.**', is_staff=True, is_active=True, date_joined=timezone.now()) newUser.save() testDBModel.testUsers.append(newUser) testDBModel.testUsersID.append(newUser.pk) ###### add Category ###### category1 = Category(name="hats") testDBModel.testCategory.append(category1) category1.save() ###### add product ###### addProducts = ["ProductA", "ProductB", "ProductC", "ProductD"] for i in range(4): # # add products newOne = Product(category=category1, name=addProducts[i], brand='brand', url='url', photo='photo', price=1.0, description='') newOne.save() testDBModel.testProducts.append(newOne) ##### ## add comments ###### for i in range(4): newOne = Comment(product=testDBModel.testProducts[i], owner=testDBModel.testUsers[i], content="null", time = timezone.now()) newOne.save() testDBModel.testComments.append(newOne) # add to wishlist first for i in range(4): newOne = WishList(product=testDBModel.testProducts[i], owner=testDBModel.testUsers[i]) newOne.save()
def add_product(request): if request.method == 'POST': name = request.POST['name'] category = request.POST['category'] description = request.POST['descrription'] price = request.POST['price'] quantity = request.POST['quantity'] img = request.FILES['photo1'] offer = request.POST['offer'] shop_id = request.user.id if offer == '': offer = 0 current_username = request.user.username per = Seller.objects.get(username=current_username) new_product = Product(name=name, category=category, description=description, price=price, quantity=quantity, rate=0, offer=offer, comment=[], img=img, shop_id=per.id) new_product.save() per.owned_products.append(new_product.id) per.save() return redirect('/dashboard')
def test_product_has_an_image_source(self): product = Product() category = Category.objects.first() product.category = category product.SKU = 123 self.assertRaises(IntegrityError, product.save)
def get(self, request): categories = Category.get_all_categories() categoryID = request.GET.get('category') if categoryID: products = Product.get_all_products_by_category_id(categoryID) else: products = Product.get_all_products() data = {'products': products, 'categories': categories} return render(request, 'index.html', data)
def create_test_product(self, name='bbc'): product_name = name profile1 = self.create_test_user("*****@*****.**").profile expectedPrice = 100 description = "Some unknown english words" category = self.create_test_category(name='xyzCategory') product = Product(name=product_name, seller=profile1, expected_price=expectedPrice, description=description, category=category) product.save() return product
def test_product_price(self): product = Product() product.product_type = '00' product_group = ProductGroup() product_group.name = 'Bouncy' product_group.save() product.product_group = product_group product.code = 'BBALL' product.name = 'Bouncy Ball' product.save() product_sellingprice = ProductSellingprice() product_sellingprice.product = product product_sellingprice.commencing_date = datetime.strptime('2012-02-01:00:00:00', '%Y-%m-%d:%H:%M:%S') product_sellingprice.set_date = datetime.strptime('2012-01-01:00:00:00', '%Y-%m-%d:%H:%M:%S') product_sellingprice.price = Money(4.00, 'EUR') product_sellingprice.save() product_sellingprice = ProductSellingprice() product_sellingprice.product = product product_sellingprice.commencing_date = datetime.strptime('2012-03-01:00:00:00', '%Y-%m-%d:%H:%M:%S') product_sellingprice.set_date = datetime.strptime('2012-01-01:00:00:00', '%Y-%m-%d:%H:%M:%S') product_sellingprice.price = Money(6.00, 'EUR') product_sellingprice.save() self.assertEqual(product.get_price(date=datetime.strptime('2012-02-02:00:00:00', '%Y-%m-%d:%H:%M:%S')), Money(4.00, 'EUR')) self.assertEqual(product.get_price(date=datetime.strptime('2012-03-02:00:00:00', '%Y-%m-%d:%H:%M:%S')), Money(6.00, 'EUR'))
def handle(self, *args, **options): r = requests.get(SKILL_URL, headers=headers) r.raise_for_status() model = r.json() menus = model['interactionModel']['languageModel']['types'] for menu in menus: if menu['name'] not in MENUS_TO_IMPORT: continue category, _ = ProductCategory.objects.get_or_create( name=menu['name']) print(menu['name']) for product in menu['values']: name = product['name']['value'] synonyms = product['name'].get('synonyms', []) synonyms_str = ','.join(synonyms) if 'id' in product and Product.objects.filter( id=product['id']).exists(): obj = Product.objects.get(id=product['id']) obj.name = name obj.synonyms = synonyms_str obj.save() else: Product(name=name, synonyms=synonyms_str, category=category, price=0).save() print(' -', product['name']['value'])
def create_test_product(self): name = "TechRe Book" seller = self.create_test_user( '*****@*****.**').profile product_price = 500 description = "Mint condition" category = self.create_test_category(name="Books") product = Product( name=name, seller=seller, expected_price=product_price, description=description, category=category, ) product.save() return product
def create_product_from_email(email, is_negotiable): user = create_user_from_email(email) product = Product(seller=user.profile) product.name = "kurkure" product.expected_price = 20 product.is_negotiable = is_negotiable product.description = "dedha hai par mera hai" product.save() return product, user
def process_item(self, item, spider): p = Product() p.title = item["title"] p.price = float(item['price'].replace(',', '.').strip()) p.image = item['image_url'] or '' p.save() return item
def test_active_manager_works(self): Product.objects.bulk_create([ Product( name='The cathedral and the bazaar', price=Decimal('10.0'), ), Product( name='Pride and Prejudice', price=Decimal('4.0'), ), Product( name='A Tale of Two Cities', price=Decimal('16.0'), active=False, ), ]) self.assertEqual(len(Product.objects.active()), 2)
def createProduct(request): try: if not Customer.objects.get(user=request.user).isAdmin: return HttpResponse('Must be admin to access.', status=status.HTTP_403_FORBIDDEN) if request.method == "GET": return HttpResponse(render(request, 'manageSite/createProduct.html', {'form': CreateProductForm}), status=200) elif request.method == "POST": productData = request.POST productImage = request.FILES allCollection = Collection.objects.all() listOfName = [] for collection in allCollection: listOfName.append(collection.collectionName) if (productData['productCollection'] not in listOfName): Collection.objects.create( collectionName=productData['productCollection']) currCollection = Collection.objects.get( collectionName=productData['productCollection']) else: currCollection = Collection.objects.get( collectionName=productData['productCollection']) newProduct = Product( productName=productData['productName'], productDescription=productData['productDescription'], productPrice=productData['productPrice'], productCollection=currCollection) newProduct.save() if productImage: addImageToProduct(productImage['productImage'], newProduct) return HttpResponse('Product created successfully', status=status.HTTP_200_OK) except DatabaseError: return HttpResponse(DatabaseErrorMessage, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return HttpResponse(str(e), status=status.HTTP_400_BAD_REQUEST)
def createProducts(request): """ On GET- returns form to create new product On POST- creates a new product with form input. On PATCH- changes specified product details with data given by user. On DELETE- deletes product given by user. """ try : # if not Customer.objects.get(user=request.user).isAdmin: # return HttpResponse('Must be admin to access.', status=status.HTTP_403_FORBIDDEN) if request.method == "GET" : return HttpResponse(render(request, "products/create-a-product.html", {'form' : NewProductForm}), status = 200) elif request.method == "POST": productData = request.POST productImage = request.FILES allCollection = Collection.objects.all() listOfName = [] for collection in allCollection: listOfName.append(collection.collectionName) if (productData['productCollection'] not in listOfName): Collection.objects.create(collectionName = productData['productCollection']) currCollection = Collection.objects.get(collectionName=productData['productCollection']) else: currCollection = Collection.objects.get(collectionName=productData['productCollection']) newProduct = Product( productName = productData['productName'], productDescription = productData['productDescription'], productPrice = productData['productPrice'], productCollection = currCollection ) newProduct.save() if productImage: addImageToProduct(productImage['productImage'], newProduct) return HttpResponse('Product created successfully', status=status.HTTP_200_OK) except DatabaseError : return HttpResponse(DatabaseErrorMessage, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return HttpResponse(str(e), status=status.HTTP_400_BAD_REQUEST)
def test_product_has_a_price(self): product = Product() category = Category.objects.first() product.category = category product.SKU = 123 product.img_src = "" product.save() self.assertTrue(hasattr(product, "price"))
def create_product(self, request): form = ProductForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data user = users.get_current_user() prod_obj = Product( description=cd['description'], min_price=cd['min_price'], due_date=cd['due_date'], owner_email=user.email() ) prod_obj.save() # so we have a key new_photo = '' new_photo_data = request.FILES.get("photo", None) if new_photo_data: for chunk in new_photo_data.chunks(): new_photo += chunk if new_photo: img = images.Image(new_photo) img.resize(height=100) clean_photo = img.execute_transforms(output_encoding=images.PNG) prod_obj.photo = db.Blob(clean_photo) prod_obj.save() return HttpResponseRedirect('/') return self.show_template('main/product_info.html', form=form)
def setUp(self): self.product_source = Product( name="Coca-Cola Classic", code="5449000000996", nutriscore="e", url="https://fr.openfoodfacts.org/produit/5449000000996/coca-cola", popularity=2802) self.product_source.save() self.product_target = Product( name="Coca-Cola Zero", code="5449000133335", nutriscore="b", url= "https://fr.openfoodfacts.org/produit/5449000133335/coca-cola-zero", popularity=181) self.product_target.save() test_user = User(email='*****@*****.**', password=None, first_name='essai', last_name='register') test_user.set_password('blabla75') test_user.save() self.target_user = User.objects.get(email='*****@*****.**')
def test_create_Product(admin_client, expected_status, creation_date, update_date, test_name, error): url = reverse("product-list") product_payload = { "id": 1, "title": "test_product", "description": "test_description", "price": 999.1, "creation_date": creation_date, } true_product = Product( id=product_payload["id"], title=product_payload["title"], description=product_payload["description"], price=product_payload["price"], creation_date=product_payload["creation_date"], ) if update_date is not None: product_payload["update_date"] = update_date true_product.update_date = update_date resp = admin_client.post(url, product_payload) assert resp.status_code == expected_status products = Product.objects.all() if error: assert len(products) == 0 assert list(resp.data.values())[0][0] == error else: assert len(products) == 1 assert assertModels(products[0], true_product) admin_client.credentials()
def shop(request): page = request.GET.get('page', 1) product_list = Paginator(Product.get_all(),24,allow_empty_first_page=True) try: products = product_list.page(page) except EmptyPage: products = product_list.page(product_list.num_pages) except PageNotAnInteger: products = product_list.page(product_list.num_pages) context = { 'title': 'Shop', 'products': products } return render(request, 'main/shop.html', context=context)
def create_product_from_obj(text, category): product_list = [] for product in json.loads(text)['hits']['hits']: if Brand.objects.filter(pk=product["_source"]["Brand"]["Id"]).__len__() > 0: brand = Brand.objects.get(pk=product["_source"]["Brand"]["Id"]) else: brand = Brand.objects.create(pk=product["_source"]["Brand"]["Id"], title=product["_source"]["Brand"]["Title"]) product_list.append(Product(pk=product["_id"], title=product["_source"]["FaTitle"], price=product["_source"]["MinPriceList"], discounted_price=product["_source"]["MinPrice"], image=product["_source"]["ImagePath"], existStatus=product["_source"]["ExistStatus"], brand=brand, parent=category)) return product_list
def add_product(request): context = {} form = ProductForm(request.POST, request.FILES) context['form'] = form if form.is_valid(): datas = form.cleaned_data name, price, city = datas['name'], datas['price'], datas['city'] quantity, availability = datas['quantity'], datas['availability'] description, pictures = datas['description'], request.FILES.getlist( 'pictures') category = datas['category'] product = Product(name=name, price=price, city=city, quantity=quantity, \ description=description, availability=availability) product.slug = slugify(product.name) product.save() # On ajoute les catégories. import karim.functions as f categories = f.parse_select_multiple(category) for cat in categories: _cat = get_object_or_404(Category, name=cat) product.category.add(_cat) # On ajoute les images. for key, img in enumerate(pictures): if key == 0: product.image = "products/" + str(img) product.save() pic = Picture(product=product, picture=img) pic.save() f.handle_upload_file("products", str(img), img) return render(request, "add_product.html", context)
def add(self, product, quantity=1, update_quantity=False, size=10.0): product__id = str(product.pk) strsize = str(int(size * 10 + 1000)) p = product__id + strsize t = Product.objects.get(pk=product) thumbnail = Product.get_path(t) if p not in self.cart: self.cart[p] = { 'quantity': 0, 'name': product.product_Name, 'price': str(product.unit_Price), 'size': str(size), 'pk': product__id, 'p': p, 'thumbnail': thumbnail, 'description': str(product.product_Description), } self.cart[p]['quantity'] += 1 self.save()
def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') product = Product( name="Coca cola 1L", code="5449000054227", nutriscore="e", url="https://fr.openfoodfacts.org/produit/5449000054227/coca-cola", popularity=561, ) product.save() product = Product( name="Coca Zéro", code="5449000133328", nutriscore="b", url= "https://fr.openfoodfacts.org/produit/5449000133328/coca-zero-coca-cola", popularity=538, ) product.save()
def categories_detail(request, slug): page = request.GET.get('page', 1, ) category_object = Category.objects.filter(slug=slug, active=True).first() if not category_object: raise Http404() product_list = Paginator(Product.get_by_slug( slug), 24, allow_empty_first_page=True) try: products = product_list.page(page) except EmptyPage: products = product_list.page(product_list.num_pages) except PageNotAnInteger: products = product_list.page(1) context = { 'title': category_object.name.title(), 'products': products } return render(request, 'main/category.html', context=context)
def new_product(): if session['role'] == 'seller': form = ProductForm() if form.validate_on_submit(): product = Product(name=form.name.data, description=form.description.data, category=form.category.data, price=form.price.data, quantity=form.quantity.data, photo_name=save_picture(form.photo.data), seller=current_user) db.session.add(product) db.session.commit() flash('Product has been added successfully!', 'check') return redirect(url_for('seller_dashboard')) return render_template('new_product.html', legend="Add Product", form=form) else: flash('Only Seller can access this page', 'warning') return redirect(url_for('customer_home'))
def action(count=None, file_path=None): if not file_path: file_path = str(settings.BASE_DIR) + '/test_data/products.xlsx' work_book = load_workbook(file_path) sheet = work_book.get_sheet_by_name('data') data = [] row = 2 while True: if count is not None and row > count: break title = sheet.cell(row=row, column=1).value price = sheet.cell(row=row, column=2).value if not title: break data.append(Product(title=title, price=price)) row += 1 Product.objects.bulk_create(data) return row - 2
from datetime import datetime from main.models import Product new_product = Product(id=1, title="test_product", description="test_description", price=888.9, creation_date=datetime.now().date())
def index(request): products = Product.get_top() context = { 'products':products } return render(request, 'main/index.html', context=context)
def setUpDb(request): User.objects.all().delete() Category.objects.all().delete() Product.objects.all().delete() WishList.objects.all().delete() FitList.objects.all().delete() Comment.objects.all().delete() Added.objects.all().delete() TempProduct.objects.all().delete() glasses = Category(name='glasses') hats = Category(name='hats') headphones = Category(name='headphones') glasses.save() hats.save() headphones.save() rayban = Product(category=glasses, name='rayban glasses', brand='rayban', url='www.rayban.com', price=129.9, description='stylish rayban', overlay='raybanol.png', photo='rayban.jpg') nike = Product(category=glasses, name='nike glasses', brand='nike', url='www.nike.com', photo='nike.jpg', overlay='nikeol.png', price=99.9, description='sporty nike') adidas = Product(category=hats, name='adidas cap', brand='adidas', url='www.adidas.com', photo='addidas.jpg', overlay='addidasol.png', price=56.9, description='adidas cap!', yoffset=-0.58) levis = Product(category=hats, name='levis hat', brand='levis', url='www.levis.com', photo='levis.jpg', overlay='levisol.png', price=67.9, description='levis hat!', yoffset=-0.58) beats = Product(category=headphones, name='beats headphones', brand='beats', url='www.beats.com', photo='beats.jpg', overlay='beatsol.png', price=256.9, description='stylish headphones!', yoffset=-0.15) sony = Product(category=headphones, name='sony headphones', brand='sony', url='www.sony.com', photo='sony.jpg', overlay="sonyol.png", price=399.9, description='high quality headphones!', yoffset=-0.15) rayban.save() nike.save() adidas.save() levis.save() beats.save() sony.save() comment = Comment(product=rayban, owner=AUser.objects.get(pk=1), time=timezone.now(), content="Very nice glasses!") comment.save() wish = WishList(owner=AUser.objects.get(pk=1), product=rayban) wish.save() fit = FitList(owner=AUser.objects.get(pk=1), product=adidas) fit.save() return HttpResponse("Success!")
region=random.choice(regions), salesman=random.choice(salesmans), ) dic[name] = client clients.append(client) time_tuple = xlrd.xldate_as_tuple( sheet.cell_value(rowIdx, SALES_COLUMN_IDX_FOR_DATE), 0) date = datetime.datetime(*time_tuple) else: name = sheet.cell_value(rowIdx, SALES_COLUMN_IDX_FOR_PRODUCT_NAME) if name in ProductDic: product = ProductDic[name] else: product = Product(name=sheet.cell_value( rowIdx, SALES_COLUMN_IDX_FOR_PRODUCT_NAME), ) ProductDic[name] = product products.append(product) # #print(sheet.cell_value(rowIdx, SALES_COLUMN_IDX_FOR_PRODUCT_TOTAL_PRICE)) transaction = Transaction( t_type='PURCHASE', product=product, client=client, date=date, volume=float( check( sheet.cell_value( rowIdx, SALES_COLUMN_IDX_FOR_PRODUCT_AMOUNT))), amount=float(
def addProduct(user, id, unit_name, unit_value, price, quantity): print 'Entro BL addProduct' product = Product(); productActual = Product.objects.get(id=id) farm = Farm.objects.all()\ .only('name','latitude','longitude','size','provider__user')\ .filter(provider__user=user) product.image_url = productActual.image_url product.description = productActual.description product.name = productActual.name product.price = price product.unit_value = unit_value product.unit_name = unit_name product.farm = farm[0] product.quantity = quantity product.save() listProduct = get_products_farm(user); return listProduct
def register_products(objs): products = json.loads(objs) print products for p in products: print p product = Product() product.name = p['name'] product.price = p['price'] product.image_url = p['image_url'] product.unit_value = p['unit_value'] product.unit_name = p['unit_name'] farm = Farm.objects.get(id=p['farm']) product.farm = farm product.description = p['description'] product.quantity = p['quantity'] product.save() print 'objeto guardado'
def setUpDb(request): User.objects.all().delete() Category.objects.all().delete() Product.objects.all().delete() WishList.objects.all().delete() FitList.objects.all().delete() Comment.objects.all().delete() Added.objects.all().delete() TempProduct.objects.all().delete() glasses = Category(name='glasses') hats = Category(name='hats') headphones = Category(name='headphones') glasses.save() hats.save() headphones.save() rayban = Product(category = glasses, name='rayban glasses', brand = 'rayban',url='www.rayban.com', price = 129.9, description='stylish rayban', overlay='raybanol.png', photo='rayban.jpg') nike = Product(category = glasses, name='nike glasses', brand = 'nike', url='www.nike.com', photo='nike.jpg',overlay='nikeol.png', price = 99.9, description = 'sporty nike') adidas = Product(category = hats, name='adidas cap', brand = 'adidas', url='www.adidas.com', photo='addidas.jpg', overlay='addidasol.png', price = 56.9, description ='adidas cap!', yoffset = -0.58) levis = Product(category = hats, name='levis hat', brand = 'levis', url='www.levis.com', photo='levis.jpg', overlay='levisol.png', price = 67.9, description ='levis hat!', yoffset = -0.58) beats = Product(category = headphones, name='beats headphones', brand = 'beats', url='www.beats.com', photo='beats.jpg', overlay='beatsol.png', price = 256.9, description='stylish headphones!', yoffset = -0.15) sony = Product(category = headphones, name='sony headphones', brand = 'sony', url='www.sony.com', photo='sony.jpg', overlay="sonyol.png", price = 399.9, description='high quality headphones!', yoffset = -0.15) rayban.save() nike.save() adidas.save() levis.save() beats.save() sony.save() comment = Comment(product = rayban, owner = AUser.objects.get(pk=1), time=timezone.now(), content="Very nice glasses!") comment.save() wish = WishList(owner=AUser.objects.get(pk=1), product=rayban) wish.save() fit = FitList(owner=AUser.objects.get(pk=1), product=adidas) fit.save() return HttpResponse("Success!")
def test_product_require_sku(self): product = Product() category = Category.objects.first() product.category = category self.assertRaises(IntegrityError, product.save)
def save_product(product_dict): product = Product(**product_dict) product.save()
def setUp(self): ###### create Users ####### users = ['UserA', 'UserB', 'UserC', 'UserD'] for i in range(4): newUser = AUser(password='', last_login=timezone.now(), is_superuser=True, username=users[i], first_name='Firstname', last_name='Lastname', email='*****@*****.**', is_staff=True, is_active=True, date_joined=timezone.now()) newUser.save() testDBModel.testUsers.append(newUser) testDBModel.testUsersID.append(newUser.pk) ###### add Category ###### category1 = Category(name="hats") testDBModel.testCategory.append(category1) category1.save() category2 = Category(name="glasses") testDBModel.testCategory.append(category2) category2.save() ###### add product ###### addProducts = ["ProductA", "ProductB", "ProductC", "ProductD"] for i in range(4): # # add products newOne = Product(category=category1, name=addProducts[i], brand='brand', url='url', photo='photo', price=1.0, description='') newOne.save() testDBModel.testProducts.append(newOne) ###### add custom product ##### newAdded = Added(owner = testDBModel.testUsers[0], product = testDBModel.testProducts[0]) newAdded.save() newAdded = Added(owner = testDBModel.testUsers[1], product = testDBModel.testProducts[1]) newAdded.save() ###### add temp product ###### tempP = TempProduct(owner = testDBModel.testUsers[0], overlay = 'overlay1ol.jpg', token = '1', category = testDBModel.testCategory[0]) tempP.save() tempP = TempProduct(owner = testDBModel.testUsers[1], overlay = 'overlay2ol.jpg', token = '2', category = testDBModel.testCategory[0]) tempP.save() testDBModel.testOverlay = ['overlay1ol.jpg', 'overlay2ol.jpg'] ##### ## add comments ###### for i in range(4): newOne = Comment(product=testDBModel.testProducts[i], owner=testDBModel.testUsers[i], content="null", time = timezone.now()) newOne.save() testDBModel.testComments.append(newOne) # add to wishlist first for i in range(4): newOne = WishList(product=testDBModel.testProducts[i], owner=testDBModel.testUsers[i]) newOne.save() # add to FitList: for i in range(4): newOne = FitList(product = testDBModel.testProducts[i], owner = testDBModel.testUsers[i]) newOne.save()