def add(request): error = False added = False if request.method == "POST": manufacturer = request.POST.get("maker") # will return empty string if the field is empty model = (request.POST.get("model")) speed = convertInt(request.POST.get("speed")) RAM = convertInt(request.POST.get("ram")) hd = convertInt(request.POST.get("hd")) price = convertInt(request.POST.get("price")) if not model or not speed or not maker or not RAM or not hd or not price: error = True # check if the user entered a model number and that no PC exists with that model number else: try: Products.objects.get(model=model) except ObjectDoesNotExist: prod = Products(maker=manufacturer, model=model, type="PC") prod.save() pc = PCs(model=prod, speed=speed, ram=RAM, hd=hd, price=price) pc.save() added = True return render(request, "products/add.html", dict(added=added, error=error))
def handle(self, *args, **options): file_path = options.get('file') if not file_path: raise CommandError('File not provided.') if not file_path.endswith('.json'): raise CommandError('Only .json file supported.') file_path = os.path.join('data', file_path) try: with open(file_path) as import_file: products = json.load(import_file) except FileNotFoundError as e: raise CommandError('File at %s was not found' % os.path.join('data', file_path)) # user = AuthUserModel.objects.filter(id=product['user_id']).first() # print(user.first_name) for product in products: # print(product['user_id']) # user = AuthUserModel.objects.filter(id=product['user_id']).first() # print(user.first_name) db_product = Products( category=product['category'], name=product['name'], description=product['description'], image_url=product['image_url'], # user_id=AuthUserModel.objects.filter(id=product['user_id']).first() user_id=product['user_id']) db_product.save()
def add(request): error = False added = False if request.method =="POST": manufacturer = request.POST.get("maker") # will return empty string if the field is empty model = (request.POST.get("model")) speed = convertInt(request.POST.get("speed")) RAM = convertInt(request.POST.get("ram")) hd = convertInt(request.POST.get("hd")) price = convertInt(request.POST.get("price")) if not model or not speed or not maker or not RAM or not hd or not price: error = True # check if the user entered a model number and that no PC exists with that model number else: try: Products.objects.get(model=model) except ObjectDoesNotExist: prod = Products(maker=manufacturer, model=model, type="PC") prod.save() pc = PCs(model= prod, speed=speed, ram=RAM, hd=hd, price=price) pc.save() added= True return render(request, "products/add.html", dict(added= added, error = error))
def dumpProducts( category_type, query, limit): ''' @params category_type: string of the category name, for example "TV" query: the search engine query, for example "SONY TV" limit: the number of data entries you want to add to database ''' target_category = Categories.objects.get(category_name = category_type) newproductstoadd = amazonListSearch(query, limit) for newproduct in newproductstoadd: product_name = newproduct[0] product_name = product_name[:95] print product_name imageURL = newproduct[1] print imageURL description = newproduct[2] print description slug = slugify(product_name) print slug price = amazonPriceSearch(product_name) print price print " " p1 = Products(product_name = product_name, image = imageURL , description = description, category = target_category, slug = slug, price = price) p1.save()
def dumpProducts(category_type, query, limit): ''' @params category_type: string of the category name, for example "TV" query: the search engine query, for example "SONY TV" limit: the number of data entries you want to add to database ''' target_category = Categories.objects.get(category_name=category_type) newproductstoadd = amazonListSearch(query, limit) for newproduct in newproductstoadd: product_name = newproduct[0] product_name = product_name[:95] print product_name imageURL = newproduct[1] print imageURL description = newproduct[2] print description slug = slugify(product_name) print slug price = amazonPriceSearch(product_name) print price print " " p1 = Products(product_name=product_name, image=imageURL, description=description, category=target_category, slug=slug, price=price) p1.save()
def setUp(self): ''' Creates the Database and one user for tests. ''' i = 1 while i <= 20: c = Categorys(category="category", ) c.save() if 1 <= 10: p = Products( product="123456" + str(i), nutrition_grade_fr=1, product_name_fr="Product" + str(i), ingredients_text_fr="Ingredients" + str(i), product_image_large="Product_img_l" + str(i), product_image_small="Product_img_s" + str(i), product_image_nutrition_large="Product_img_n_l" + str(i), product_image_nutrition_small="Product_img_n_s" + str(i), stores="Stores" + str(i), url="Url" + str(i), ) cat = Categorys.objects.get(category="category") p.category = cat p.save() else: p = Products( product="123456" + str(i), nutrition_grade_fr=2, product_name_fr="Product" + str(i), ingredients_text_fr="Ingredients" + str(i), product_image_large="Product_img_l" + str(i), product_image_small="Product_img_s" + str(i), product_image_nutrition_large="Product_img_n_l" + str(i), product_image_nutrition_small="Product_img_n_s" + str(i), stores="Stores" + str(i), url="Url" + str(i), ) cat = Categorys.objects.get(category="category") p.category = cat p.save() i += 1 user = CustomUser.objects.create(email="*****@*****.**", first_name="first_name", second_name="second_name", password="******") user = CustomUser.objects.get(email=user) chosen_product = Products.objects.get(product="1234561") remplacement_product = Products.objects.get(product="1234562") history = History.objects.create( user=user, chosen_product=chosen_product, remplacement_product=remplacement_product)
def addProduct(request): if request.user.is_authenticated: try: product = Products(product_name=request.POST['product_name']) except Exception as e: print(e) return HttpResponse(status=404) else: product.save() return HttpResponseRedirect('/products/index/') else: return HttpResponse(status=401)
def test_results_page_shows(self): ''' Tests the search page, and the products page. ''' i = 1 while i <= 20: c = Categorys( category="category", ) c.save() if 1 <= 10: p = Products( product="123456"+str(i), nutrition_grade_fr= 1, product_name_fr="Product"+str(i), ingredients_text_fr="Ingredients"+str(i), product_image_large="Product_img_l"+str(i), product_image_small="Product_img_s"+str(i), product_image_nutrition_large="Product_img_n_l"+str(i), product_image_nutrition_small="Product_img_n_s"+str(i), stores="Stores"+str(i), url="Url"+str(i), ) cat = Categorys.objects.get(category="category") p.category = cat p.save() else: p = Products( product="123456"+str(i), nutrition_grade_fr= 2, product_name_fr="Product"+str(i), ingredients_text_fr="Ingredients"+str(i), product_image_large="Product_img_l"+str(i), product_image_small="Product_img_s"+str(i), product_image_nutrition_large="Product_img_n_l"+str(i), product_image_nutrition_small="Product_img_n_s"+str(i), stores="Stores"+str(i), url="Url"+str(i), ) cat = Categorys.objects.get(category="category") p.category = cat p.save() i += 1 self.driver.get(self.live_server_url) self.driver.find_element_by_id("searchForm").send_keys('Product') self.driver.find_element_by_id("searchForm").submit() self.assertTrue(self.driver.title == 'Page Products')
def setUp(self): cat = Categorys.objects.create(category="test1") p = Products( product="123456", nutrition_grade_fr=1, product_name_fr="Product", ingredients_text_fr="Ingredients", product_image_large="Product_img_l", product_image_small="Product_img_s", product_image_nutrition_large="Product_img_n_l", product_image_nutrition_small="Product_img_n_s", stores="Stores", url="Url", ) cat = Categorys.objects.get(category="test1") p.category = cat p.save()
def post(self, request): cat_type_id = request.data.get(RequestKeys.CATEGORY_TYPE.value, None) no_of_products = request.data.get(RequestKeys.NUMBER_OF_PRODUCTS.value, None) if cat_type_id and no_of_products: cat_type = Categories.objects.get(id=cat_type_id) products = [ Products(category=cat_type, code=str(uuid.uuid4())) for i in range(no_of_products) ] Products.objects.bulk_create(products) return Response(ResponseHandler.get_result( SuccesMessages.PRODUCTS_GENERATED.value % no_of_products), status=status.HTTP_200_OK) else: return Response(ResponseHandler.get_result( FailureMessages.INVALID_INPUT.value), status=status.HTTP_400_BAD_REQUEST)
def add_product(request): params = json.loads(request.POST['json']) name = params['name'] price = params['precio'] description = params['description'] date_up = datetime.now() if not name: return JsonResponse({}, status=400) product = Products() product.name = name product.description = description product.price = price product.date_up = date_up product.save() response = { 'created': True } return JsonResponse(response, status=200)
def test_product(self): category = Category.objects.create(cat="pizzas") self.assertEqual(category.cat, "pizzas") product = Products.objects.create( id_code=2344393, food_name="pizzas", nutrition_grade="a", image_url="www.oeoeieoirie.com", food_link="www.didjdijddj.com", image_nutrition_url="www.oeoeouou.fr") categ = Category.objects.get(cat=category.cat) product.category.add(categ) product.save() self.assertEqual(product.id_code, 2344393) self.assertEqual(product.food_name, "pizzas") self.assertEqual(product.nutrition_grade, "a") self.assertEqual(product.image_url, "www.oeoeieoirie.com") self.assertEqual(product.food_link, "www.didjdijddj.com") self.assertEqual(product.image_nutrition_url, "www.oeoeouou.fr") cate = product.category.all() cate2 = str(cate[0]) self.assertEqual(cate2, "pizzas") self.assertEqual(product.food_name, Products.__str__(product)) self.assertEqual(category.cat, Category.__str__(category))
def handle(self, *args, **options): help = "Insert all products an relations in the models tables." print("Debout du travail!...") DataFiles.download_and_clean_all_products(DataFiles) products_to_insert = DataFiles.products_to_inser print( "Nous avons ", len(products_to_insert), "produits téléchargées et nettoyées!", ) print("Insértion de tous les produits dans la base de données!") try: for data_dict in products_to_insert: c = Categorys(category=data_dict["category"]) c.save() if data_dict["nutrition_grade_fr"] == "a": nut = 1 if data_dict["nutrition_grade_fr"] == "b": nut = 2 if data_dict["nutrition_grade_fr"] == "c": nut = 3 if data_dict["nutrition_grade_fr"] == "d": nut = 4 if data_dict["nutrition_grade_fr"] == "e": nut = 5 p = Products( product=str(data_dict["product"]), nutrition_grade_fr=nut, product_name_fr=data_dict["product_name_fr"], ingredients_text_fr=data_dict["ingredients_text_fr"], product_image_large=data_dict["product_image_large"], product_image_small=data_dict["product_image_small"], product_image_nutrition_large=data_dict[ "product_image_nutrition_large" ], product_image_nutrition_small=data_dict[ "product_image_nutrition_small" ], stores=data_dict["stores"], url=data_dict["url"], ) cat = Categorys.objects.get(category=data_dict["category"]) p.category = cat p.save() except: raise CommandError( "Ups une erreur est arrivé, insertion aborté!! sur le produit", p.product_name_fr, ) self.stdout.write( self.style.SUCCESS( "Les produits sont, à present, sauvegardées dans la base de données!" ) )
import random import sys, os os.environ['DJANGO_SETTINGS_MODULE'] = 'ecommerce.settings' from django.conf import settings from products.models import Products,PCs, Laptops, Printers makers = ["Apple", "HP", "Lenovo", "Dell", "Sony"] printerType=["laser", "ink-jet"] colorVal = [True,False] # add 100 pcs for i in range(1,100): product = Products(maker=makers[random.randint(0,4)], model=i, type="PC") product.save() ram = random.uniform(1, 16) speed = random.uniform(1,4) hd = random.randint(100,1000) price = random.uniform(500,2000) ram = float(format(ram, ".2f")) speed = float(format(speed, ".2f")) price = float(format(price, ".2f")) pc = PCs(model=product, ram=ram,speed=speed, hd=hd, price=price) pc.save() # add 100 laptops for i in range(100,200): product = Products(maker=makers[random.randint(0,4)], model=i, type="Laptop") product.save() ram = random.uniform(1, 16) speed = random.uniform(1,4) hd = random.randint(100,1000) price = random.uniform(500,2000) screen = random.uniform(10,22)
def addProduct(request): if request.method=='POST': print request.POST ##print request.POST product_id=request.POST['productid'] subcategory_count=request.POST['count'] if (subcategory_count==""): subcategory_count=0 subcategory_count=int(subcategory_count) subcategory_count+=1 category=request.POST['category'] subcategory=[] if (subcategory_count>0): for each in range(1,subcategory_count): temp=('subcategory'+str(each)) subcategory.append(request.POST[temp]) print subcategory #form Category_objects if (len(subcategory)==1): category_objects=Category.objects.filter(category_name=category,subcategory_1=subcategory[0]) elif (len(subcategory)==2): category_objects=Category.objects.filter(category_name=category,subcategory_1=subcategory[0],subcategory_2=subcategory[1]) elif (len(subcategory)==3): category_objects=Category.objects.filter(category_name=category,subcategory_1=subcategory[0],subcategory_2=subcategory[1],subcategory_3=subcategory[2]) else: category_objects=Category.objects.filter(category_name=category,subcategory_1=None,subcategory_2=None,subcategory_3=None) """saved_category=[] saved_category.append(category_objects.subcategory_1); saved_category.append(category_objects.subcategory_2); saved_category.append(category_objects.subcategory_3); for each in range(0,len(subcategory)): if(saved_category[each]!=subcategory[each]): category_objects=create_new_category(category,subcategory)""" if len(category_objects) == 0: category_objects=create_new_category(category, subcategory) category_id=category_objects.id else: category_id=category_objects[0].id brand=request.POST['brand'] unit_price=request.POST['unit_price'] model=request.POST['model'] description=request.POST['description'] product_name=request.POST['product_name'] currenttime=datetime.datetime.now() product_item=Products() product_item.product_name=product_name product_item.product_id=product_id product_item.category_id=category_id product_item.brand=brand product_item.model_no=model product_item.short_description=description product_item.baseUnitPrice=unit_price product_item.arrival=currenttime product_item.save() print product_item return HttpResponseRedirect('/Home/Admin/')
pwd = os.path.dirname(os.path.realpath(__file__)) sys.path.append(pwd + '../') #在manage.py中 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "beenquickServer.settings") import django django.setup() from db_tools.axf_json import JSONSTR from products.models import Products data = eval(JSONSTR)['data'] products = data['products'] for k, v in products.items(): for product in v: p = Products() p.id = product['id'] p.name = product['name'] p.longname = product['long_name'] p.store_nums = product['store_nums'] p.specifics = product['specifics'] p.attribute = product['attribute'] p.sort = product['sort'] p.brand_id = product['brand_id'] p.brand_name = product['brand_name'] p.hot_degree = product['hot_degree'] p.safe_day = product['safe_day'] p.safe_unit = product['safe_unit'] p.market_price = product['market_price'] p.partner_price = product['partner_price'] p.pre_img = product['pre_img']
import random import sys, os os.environ['DJANGO_SETTINGS_MODULE'] = 'ecommerce.settings' from django.conf import settings from products.models import Products, PCs, Laptops, Printers makers = ["Apple", "HP", "Lenovo", "Dell", "Sony"] printerType = ["laser", "ink-jet"] colorVal = [True, False] # add 100 pcs for i in range(1, 100): product = Products(maker=makers[random.randint(0, 4)], model=i, type="PC") product.save() ram = random.uniform(1, 16) speed = random.uniform(1, 4) hd = random.randint(100, 1000) price = random.uniform(500, 2000) ram = float(format(ram, ".2f")) speed = float(format(speed, ".2f")) price = float(format(price, ".2f")) pc = PCs(model=product, ram=ram, speed=speed, hd=hd, price=price) pc.save() # add 100 laptops for i in range(100, 200): product = Products(maker=makers[random.randint(0, 4)], model=i, type="Laptop") product.save() ram = random.uniform(1, 16) speed = random.uniform(1, 4) hd = random.randint(100, 1000)
def search(request): if 'name' in request.GET and request.GET['name']: name = request.GET['name'] manufacturer = request.GET['manufacturer'] p = Products(name=name,manufacturer=manufacturer) p.save()