def setUp(self): # create Users self.test_user1 = User.objects.create_user(username='******', password='******') self.test_user2 = User.objects.create_user(username='******', password='******') # data for filters self.name_length = 3 self.price_size = 50 # create Products data_dict = { 'product1': 1, 'product2': 10, 'pr': 33, 'product4': 43, 'product6': 90 } products = [ Product(name=name, price=price, create_by=self.test_user2) if index % 2 else Product(name=name, price=price, create_by=self.test_user1) for index, (name, price) in enumerate(data_dict.items()) ] Product.objects.bulk_create(products)
def handle(self, *args, **options): with transaction.atomic(): Customer.objects.bulk_create([ Customer(name='Jane Doe'), Customer(name='John Doe'), ]) jane, john = Customer.objects.order_by('name') Product.objects.bulk_create([ Product(name='Apple', price=Decimal('2.50'), inventory=4), Product(name='Kiwi', price=Decimal('5.00'), inventory=3), Product(name='Orange', price=Decimal('3.00'), inventory=5), ]) apple, kiwi, orange = Product.objects.order_by('name') # Jane has placed two orders order = Order.objects.create_order( customer=jane, is_shipped=True, created_at=datetime.fromisoformat('2019-04-06T16:00:00+02:00'), products=[apple, kiwi], ) Order.objects.create_order( customer=jane, is_shipped=False, created_at=datetime.fromisoformat('2019-04-10T09:00:00+02:00'), products=[apple, kiwi], ) # John has placed three orders order = Order.objects.create_order( customer=john, is_shipped=True, created_at=datetime.fromisoformat('2019-03-31T15:00:00+01:00'), products=[apple, orange], ) order = Order.objects.create_order( customer=john, is_shipped=True, created_at=datetime.fromisoformat('2019-04-01T13:00:00+02:00'), products=[orange, kiwi], ) Order.objects.create_order( customer=john, is_shipped=False, created_at=datetime.fromisoformat('2019-04-07T12:00:00+02:00'), products=[apple], ) SalesTarget.objects.bulk_create([ SalesTarget(year=2019, month=3, target=Decimal('10.00')), SalesTarget(year=2019, month=4, target=Decimal('12.00')), ])
def test_order_total(self): """ test if grand total takes in consideration correct delivery fee and sums up lineitems correctly """ # delivery to Ireland product = Product(name="product", price=10) product2 = Product(name="product2", price=5) product.save() product2.save() order = Order( full_name="test", email="test", phone_number="12", country="IE", postcode="test", town_or_city="test", street_address1="test", street_address2="test", county="test", original_bag="test", ) order.save() # check grand total calculation orderlineitem = OrderLineItem( order=order, product=product, quantity=2, ) orderlineitem2 = OrderLineItem( order=order, product=product2, quantity=2, ) orderlineitem.save() orderlineitem2.save() tot_first_line = product.price*orderlineitem.quantity tot_second_line = product2.price*orderlineitem2.quantity total = tot_first_line + tot_second_line ie_delivery_fee = total * ( settings.IRL_STANDARD_DELIVERY_PERCENTAGE/100 ) grand_total = (ie_delivery_fee + total) self.assertEqual(order.grand_total, grand_total) # same, order, delivery to EU order.country = "DE" order.save() orderlineitem.save() orderlineitem2.save() delivery_fee = total * settings.STANDARD_DELIVERY_PERCENTAGE / 100 grand_total = (delivery_fee + total) self.assertEqual(order.grand_total, grand_total)
def add_products(): db_session.add( Product('Computer', 15, 'Xiaomi Laptop very convenient and easy to use', 'laptop.jpeg')) db_session.add( Product( 'Mobile', 10, 'This model of Samsung Galaxy Note8 is luxurious and trendy this season', 'note8.jpeg')) db_session.add( Product('Watch', 5, 'Xiaomi Laptop very convenient and easy to use', 'watch.jpg')) db_session.commit() return "Items added..."
def setUp(self): self.test_product = { 'id': '123', 'nutrition_grades': "a", 'product_name': "product nametest", 'generic_name': "gen_name description", 'image_front_url': "URL IMAGE", 'image_nutrition_url': "url nutri", 'url': "url", 'categories_hierarchy': ['cat1', 'cat2', 'cat3'], } CustomUser(first_name='first name test', email='*****@*****.**', password='******').save() Product(id=self.test_product['id'], nutriscore=self.test_product['nutrition_grades'], name=self.test_product['product_name'], summation=self.test_product['generic_name'], picture=self.test_product['image_front_url'], nutrition=self.test_product['image_nutrition_url'], external_link=self.test_product['url']).save() self.client = Client()
def test_add_to_cart_when_product_is_already_in_the_cart(self): ''' test add to cart when the product is already in the cart ''' # create a Product item = Product(name="Product", available_stock="100", content="product content", price="30", image="img.jpg", num_of_ratings="5", average_rating="5") # save the product item.save() # post product and quantity to cart page = self.client.post("/cart/add/{0}".format(item.id), data={'quantity': '3'}, follow=True) # post same product and quantity to cart page = self.client.post("/cart/add/{0}".format(item.id), data={'quantity': '1'}, follow=True) # check the status code is 200 self.assertEqual(page.status_code, 200) # check Template Used is products.html self.assertTemplateUsed(page, "products.html")
def test_string_method_on_line_item_model_returns_sku(self): testproduct = Product(sku='test_sku') testorder = Order() orderlineitem = OrderLineItem(product=testproduct, order=testorder) self.assertEqual( str(orderlineitem), f'SKU {testproduct.sku} on order {testorder.order_number}')
def setUp(self): user = { "username": "******", "password1": "P4sswordVeryS€cure@", "password2": "P4sswordVeryS€cure@", "email": "*****@*****.**" } self.client.post('/consumer/signup', data=user) self.token = self.client.post('/user/login', data={ 'email': '*****@*****.**', 'password': '******' }).json()['key'] self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token) cat = Category(name='category') cat.save() cat = Category(name='category2') cat.save() p = Product(name='product') p.save() p.categories.set([Category.objects.all()[0]]) p.save() store = Store(name='store', pnt=GEOSGeometry('POINT(0 0)', srid=SRID)) store.save()
def import_data(data, user, csvfile_data): req_fields = ['title', 'description', 'price', 'rating', 'status'] python_csv_object = csv.DictReader(csvfile_data.read().splitlines()) for i, rowData in enumerate(python_csv_object): new_product = Product() row = {} for k in rowData.keys(): row[k.replace(' ', '_').lower()] = rowData[k] if i == 0: if not all(map(lambda v: v in row.keys(), req_fields)): break for field in req_fields: setattr(new_product, field, row[field]) new_product.created_by = user new_product.save() subcat_ids = data.getlist('category') if subcat_ids: for cid in subcat_ids: subcat = CatalogCategory.objects.get(id=cid) ProductCategory.objects.create(product=new_product, category=subcat)
def test_get_product_detail_page(self): product = Product(title="TestTitle", price="5") product.save() page = self.client.get("/products/{0}/".format(product.id)) self.assertEqual(page.status_code, 200) self.assertTemplateUsed(page, "product_detail.html")
def _import(cls, products): for product in products: p = Product( is_customizable=product['is_customizable'], delivery=product['delivery'], kids=product['kids'], name=product['name'], relative_url=product['relative_url'], discount_percentage=product['discount_percentage'], kid_adult=product['kid_adult'], free_porto=product['free_porto'], image=product['image'], sizes=product['sizes'], package=product['package'], price=cls._clean_float(product['price']), discount_type=product['discount_type'], product_labels=product['product_labels'], url=product['url'], online=product['online'], price_old=cls._clean_float(product['price_old']), currency=product['currency'], img_url=product['img_url'], id=product['id'], women=product['women'], ) p.save()
def add_prod(request): if request.method == 'POST': user = request.user.username user = Account.objects.get(username=user) name = request.POST.get('nameProd') price = float(request.POST.get('priceProd')) cat = request.POST.get('category') desc = request.POST.get('desc') quan = int(request.POST.get('quantityProd')) pic = request.FILES['myfile'] if 'myfile' in request.FILES else False newP = Product( title=name, price=price, quantity=quan, category=cat, description=desc, ) if (pic != False): fs = FileSystemStorage("static/images") fs.save(pic.name, pic) fileurl = "static/images" + fs.url(pic) newP.img = fileurl newP.store = user.store newP.save() return redirect('inventory') else: return render(request, 'inventory.html')
def save_products(self, products): """ Same as with save_categories, this function saves really quickly a lot of products to DB. The format used is the same that scrape_product produces. """ category = Category.objects.get(name=products["category_name"]) product_models = [ Product(name=product['name'], url=product['url'], image=product['image'], nutriscore=product['nutriscore'], category=category, energy=product['energy'], proteins=product['proteins'], fat=product['fat'], saturated_fat=product['saturated_fat'], sugar=product['sugar'], salt=product['salt']) for product in products['products'] ] Product.objects.bulk_create( product_models, # We ignore the conflicts # and just don't add them. # This happens when updating. # Due to the API, it can also # happen during normal init. ignore_conflicts=True)
def setUp(self): category = Category(name='maria_sharia') category.save() product = Product(name='name', description='description', offer='99.00') product.save()
def add_non_existing_item(text, amount, user): product = Product(name=text) product.save() new_kitchen = ProductInKitchen(product=product, owner=user, quantity=amount) new_kitchen.save()
def product_accept_add(request): if request.user.is_superuser: if request.method == 'POST': product_id = request.POST['product_id'] product_name = request.POST['product_name'] product_image = request.POST['product_image'] company = request.POST['company'] product_description = request.POST['product_description'] quantity = request.POST['quantity'] price = request.POST['price'] product = Product(product_id=product_id, product_name=product_name, product_image=product_image, company=company, product_description=product_description, quantity_in_stock=quantity, sell_price=price) product.save() return redirect('/products') messages.add_message(request, messages.INFO, 'Error! Please refill the form to add a product') return redirect('/admin/products/add') return HttpResponse("You don't have permission to view this page")
def test_removing_an_item_from_the_cart(self): ''' test removing an item from the cart ''' # create a Product item = Product(name="Product", available_stock="100", content="product content", price="30", image="img.jpg", num_of_ratings="5", average_rating="5") # save the product item.save() # post product and quantity to cart page = self.client.post("/cart/add/{0}".format(item.id), data={'quantity': '3'}, follow=True) # post same product and quantity to cart page = self.client.post("/cart/adjust/{0}".format(item.id), data={'quantity': '0'}, follow=True) # check the status code is 200 self.assertEqual(page.status_code, 200) # check Template Used is products.html self.assertTemplateUsed(page, "cart.html")
def setUp(self): """Method called to prepare the test fixture.""" self.options = ChromeOptions() # self.options.add_experimental_option("excludeSwitches", # ["enable-logging"]) self.options.add_argument('--headless') self.options.add_argument('--disable-gpu') self.options.add_argument('--remote-debugging-port=9222') self.options.add_argument('--window-size=1920x1080') self.browser = Chrome(chrome_options=self.options) User = get_user_model() self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.category = Category(id_category="1à", name="category_test", products=1, visible=True) self.category.save() for id_product in range(7): self.product = Product(id_product="key%s" % id_product, product_name_fr="test_%s" % id_product, nutriscore_score=0, nutriscore_grade='A', brands='brand_test') self.product.save() self.product.categories.add(self.category)
def save_product(request): if request.method == 'POST': product_specification = calculate_product_specification(request) product_list_names = calculate_product_list_names(product_specification) product = Product(product_name=product_specification['product_name'], user_id=product_specification['user_id'], is_base_product=product_specification['is_base_product'], is_optional_product=product_specification['is_optional_product'], is_custom_product=product_specification['is_custom_product'], desired_amount=product_specification['desired_amount'], current_amount=product_specification['current_amount'], lacking_amount=product_specification['lacking_amount']) products = get_products_for(request.user.id) if is_product_assigned_to_any_product_list(product_specification): product.save() messages.success(request, 'You have added new product to ' + product_list_names) else: messages.error(request, 'Please specify at least one product list') use_as_default_tab = True if not is_product_assigned_to_any_product_list(product_specification) else False context = { 'base_products': products['base_products'], 'optional_products': products['optional_products'], 'custom_products': products['custom_products'], 'base_product_active': product_specification['is_base_product'], 'optional_product_active': product_specification['is_optional_product'], 'custom_product_active': product_specification['is_custom_product'], 'use_as_default_tab': use_as_default_tab } return render(request, 'accounts/dashboard.html', context)
def sales(request, pk): object_list = Product.my_query.active_with_qty() instance = get_object_or_404(RetailOrder, id=pk) form = SalesForm(instance=instance) search_name = request.GET.get('search_name', None) barcode = request.GET.get('barcode', None) object_list = object_list.filter( Q(title__icontains=search_name) | Q(sku__icontains=search_name) ).distinct() if search_name else object_list if barcode: RetailOrderItem.barcode(request, instance) if request.POST: form = SalesForm(request.POST, instance=instance) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('pos:sales', kwargs={'pk': pk})) form_paid = Product(request.POST) if form_paid.is_valid(): form_paid.save() return HttpResponseRedirect(reverse('pos:sales', kwargs={'pk': pk})) object_list = object_list[:10] context = locals() return render(request, 'PoS/sales.html', context)
def publish(request): if request.method == 'GET': return render(request, 'publish.html') elif request.method == 'POST': app_name = request.POST['app_name'] description = request.POST['description'] app_link = request.POST['app_link'] try: app_icon = request.FILES['app_icon'] screen_shot = request.FILES['app_screen_shot'] product = Product() product.app_name = app_name product.description = description product.app_link = app_link product.app_icon = app_icon product.screen_shot = screen_shot product.publish_date = timezone.datetime.now() product.hunter = request.user product.save() return redirect('home') except Exception as err: return render(request, 'publish.html', {'image_error': 'Please upload images.'})
def add_products(): db_session.add( Product( 'Computer', 15, 'Mac book pro - a product of Apple. Nice looking and easy to use', 'computer.jpeg')) db_session.add( Product('Smartphone', 10, 'Android OnePlus5 - quite interesting purchase in this month', 'oneplus5.jpg')) db_session.add( Product('Watches', 5, 'Golden watches with GPS tracker and calories counter', 'watches.png')) db_session.commit() return "Items added"
def handle(self, *args, **kwargs): # load categories data categories = load_json_data('categories') ProductCategory.objects.all().delete() for category in categories: new_category = ProductCategory(name=category['name'], description=category['description']) new_category.save() # load products data products = load_json_data('products') Product.objects.all().delete() for p in products: # get category_id by name category_id = ProductCategory.objects.get(name=p['category']).id # add new product new_product = Product(category_id=category_id, name=p['name'], short_desc=p['short_desc'], description=p['description'], price=p['price'], quantity=p['quantity']) new_product.save() # add image to related product img = ProductImage(product_id=new_product.id, image=p['image']) img.save()
def add_to_cart(request, product_id): quantity = int(request.POST.get('quantity')) cart = request.session.get('cart', {}) cart_item_qty = cart.get(product_id) if cart_item_qty: cart[product_id] += quantity else: cart[product_id] = cart.get(product_id, quantity) #Persisting cart to database for logged in users if request.user.is_authenticated: cart_model, created = Cart.objects.get_or_create(user=User( id=request.user.id)) #Finds the matching product if none adds, updates quantity and saves to database cart_line_item, created = CartLineItem.objects.get_or_create( cart=Cart(id=cart_model.id), product=Product(id=product_id)) cart_line_item.quantity = quantity cart_line_item.save() cart['id'] = cart_model.id request.session['cart'] = cart return redirect(reverse('products'))
def crawl(item): url_continente = 'https://www.continente.pt/pt-pt/public/Pages/searchresults.aspx?k=' response = requests.get(url_continente + item) html_soup = BeautifulSoup(response.text, 'html.parser') continente_products = html_soup.find_all("div", {'class': 'productBoxTop'}) item_list = [] for product in continente_products: name_and_size = product.find("div", {'class': "containerDescription"}) name = name_and_size.find("a").text size = name_and_size.find("div", {'class': "subTitle"}).text.lower() price = clean_price( product.find("div", { 'class': "priceFirstRow" }).text) image = product.find("div", {'class': "image"}) im = Image.open(urllib2.urlopen(image.find("img")['data-original']), mode='r') product = Product(name=name, picture=get_image_name(im), size=size, price=Decimal(price.replace(",", ".")), update_time=datetime.now(), valid=False) item_list.append({"product": product, "image": im}) for item in item_list: item["product"].save() save_image(item["image"], item["product"].picture)
def create(request): error = 'Have Some Error ' context = { 'error': error } if request.method == "POST": if request.POST['title'] and request.POST['body'] and request.POST['urls'] and request.FILES['image'] and \ request.FILES['icon']: # create Product Objects product = Product() product.title = request.POST['title'] product.body = request.POST['body'] if request.POST['urls'].startswith('http://') or request.POST['urls'].startswith('https://'): product.url = request.POST['urls'] else: product.url = 'http://' + request.POST['urls'] product.icon = request.FILES['icon'] product.image = request.FILES['image'] product.pub_date = timezone.datetime.now() product.hunter = request.user product.save() return redirect("home") else: return render(request, 'products/create.html', context) else: return render(request, 'products/create.html')
def approve(request, *args, **kwargs): if request.user.is_authenticated and request.user.is_superuser: id_inc = kwargs["id_inc"] qs = pending.objects.all() for obj in qs: # print(obj.id_inc) if int(obj.id_inc) == int(id_inc): # print("heyyyyy") new_obj = Product() new_obj.user_name = obj.user_name new_obj.category = obj.category new_obj.name = obj.name new_obj.desc = obj.desc new_obj.contact_email = obj.contact_email new_obj.contact_phone = obj.contact_phone new_obj.address = obj.address new_obj.image = obj.image new_obj.price = obj.price new_obj.save() obj.delete() return HttpResponseRedirect('../../pending') break return HttpResponseRedirect('../../pending') else: return HttpResponseRedirect('../../../')
def list(request): document = Document.objects.filter(user_id=request.user.id)[:1] if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Product(user=request.user, title=request.POST['title'], docfile=request.FILES['docfile'], active=request.POST['active'], description=request.POST['description'], quantity=request.POST['quantity'], zip_Code=request.POST['zip_Code'], address=request.POST['address'], expire_date=request.POST['expire_date']) newdoc.save() return redirect('products.views.post_detail_list', pk=newdoc.pk) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page return render_to_response('products/list.html', { 'document': document, 'form': form }, context_instance=RequestContext(request))
def setUpTestData(cls): """Method called to prepare the test fixture.""" cls.category = Category( id_category="1a", name="category_test", products=1, visible=True ) cls.category.save() cls.User = get_user_model() cls.user = cls.User.objects.create_user( username='******', email='*****@*****.**', password='******' ) nb_products = 11 for id_product in range(nb_products): cls.product = Product( id_product="key%s" % id_product, product_name_fr="test_%s" % id_product, nutriscore_score=0, nutriscore_grade='A' ) cls.product.save() cls.product.categories.add(cls.category) cls.product.favorites.add(cls.user) cls.client_login = Client(HTTP_REFERER=reverse('home')) cls.logged_in = cls.client_login.login( username='******', password='******')
def test_home_view(self): """ This test makes sure the home page is rendered correctly. """ product = Product(name='vine', price=12.99) product.save() products = Product.objects.all() page = self.client.get('/', {'products': products}) self.assertEquals(page.status_code, 200)