def post(self, request): if "fix" in request.POST: Category.fix_tree() return redirect("category_tree") # Ajax response to move node p = request.POST tree_move(p["node"], p["target"], p["previous"], p["position"] == "inside") return JsonResponse("OK", safe=False)
def setUpClass(cls): super(BaseModelTestCase, cls).setUpClass() coupon = Coupon(code='sale', valid_from=datetime.now(), discount=10, active=True, valid_to=datetime.now() + timedelta(days=10)) coupon.save() cls.order_sale = Order(first_name='Имя', last_name='Фамилия', email='*****@*****.**', address='Улица, дом 1', postal_code='123', city='Город', discount=10, coupon=coupon) cls.order_sale.save() cls.order = Order(first_name='Имя', last_name='Фамилия', email='*****@*****.**', address='Улица, дом 1', postal_code='123', city='Город') cls.order.save() category = Category(name='category_name', slug='category_slug') category.save() product_1 = Product(category=category, name='product_1', slug='slug_1', price=5, stock=1) product_2 = Product(category=category, name='product_2', slug='slug_2', price=5, stock=1) product_1.save() product_2.save() cls.order_item_1 = OrderItem( order=cls.order, product=product_1, price=product_1.price, ) cls.order_item_2 = OrderItem(order=cls.order, product=product_2, price=product_2.price, quantity=5) cls.order_item_1.save() cls.order_item_2.save() cls.order_sale_item = OrderItem(order=cls.order_sale, product=product_2, price=product_2.price, quantity=5) cls.order_sale_item.save()
def test_get_absolute_url_book(self): category = Category(name='History') category.save() book = Book(category=category, title='The Fire Next Time', slug='the-fire-next-time', author='James Baldwin', publishing_house='Ace Books', price=11.99, release_date=datetime.now(), pages=412) book.save() self.assertEqual(book.get_absolute_url(), f'/shop/{book.id}/{book.slug}/')
def handle(self, *args, **options): pin = Pinyin() MONGO_URI = 'mongodb://localhost:27017' MONGO_DB = 'chinese_food' mongo_client = pymongo.MongoClient(MONGO_URI) db = mongo_client[MONGO_DB] categories = set() for food in db.food.find({}): categories.add(food['category']) categories = list(categories) # 虚构了几个餐厅 restaurants = ['阿坤私房菜', '橘子餐厅', '北欧时光·清真', '辣一天川小館', '川人百味'] categories = [Category(name=cat, slug=pin.get_pinyin(cat)) for cat in categories] restaurants = [Restaurant(name=res) for res in restaurants] for category in categories: category.save() for res in restaurants: res.save() for category in categories: for food in db.food.find({'category': category.name}): product = Product.objects.create( category=category, name=food['name'], slug=slugify(pin.get_pinyin(food['name'])), image='/static/food_images/{}/{}.jpg'.format( category.name, food['name'] ), kouwei=food['kouwei'], gongyi=food['gongyi'], restaurant=random.choice(restaurants), description=food['intro'] or 'no description.', price=random.randint(10, 100)) product.save()
def category_add_view(request): get_permission(request) if request.method == 'POST': user = request.user category_form = CategoryForm(request.POST) if category_form.is_valid(): cat = Category() category_form.save(cat, user) categorys = Category.objects.all() ctx = { 'result': 'success', 'message': message("Категория добавлена!", request) } update(request, categorys, ctx) return JsonResponse(ctx) else: category_form_response = render_template( 'shopadmin_category_form.html', {'category_form': category_form}, request) return JsonResponse({ 'result': 'error', 'category_form': category_form_response })
def handle(self, *args, **options): print('shop is working!') Category.objects.all().delete() for i in all_ctgr: c = Category() c.name = i c.save() print(c) Product.objects.all().delete() for i in phones: p = Product() p.name = i p.category = c p.save() '''Product.objects.all().delete()
def get_context_data(self, **kwargs): context = super(CategoryShopsView, self).get_context_data(**kwargs) category_id = kwargs.get("category_id", 0) category = Category.get_by_unique(id=category_id) shops = category.shop_set.all() context['shops'] = shops context['category'] = category return context
def handle(self, *args, **options): categories = load_from_json('categories') Category.objects.all().delete() for category in categories: new_category = Category(**category) new_category.save() products = load_from_json('products') Product.objects.all().delete() for product in products: category_name = product["category"] _category = Category.objects.get(name=category_name) product['category'] = _category new_product = Product(**product) new_product.save()
def main_cat(title, author, parent=None): cat = Category() cat.author = author cat.title = title cat.parent = parent cat.save() return cat
def addcategory(): if request.method == "POST": category = request.form.get('category') objcategory = Category(category) db.session.add(objcategory) db.session.commit() flash(f'{category} added to database, success') return redirect(url_for('products.addcategory')) return render_template('products/addbrand.html', category='category')
def products(): category = Category(name='doesnotmatter') return [ Product(category=category, code='CODE1', title='Product #1', price=15.00), Product(category=category, code='CODE2', title='Product #2', price=19.00), Product(category=category, code='CODE3', title='Product #3', price=12.00), Product(category=category, code='CODE4', title='Product #4', price=5.00), Product(category=category, code='CODE5', title='Product #5', price=10.00), Product(category=category, code='CODE6', title='Product #6', price=35.00), ]
def products_seeder(times=5): """ Populate the model Product with fake data Parameters ---------- times Number of new data sets for the model """ for seed in range(times): name = "producto_" + str(seed) summary = fake.paragraph(nb_sentences=3, variable_nb_sentences=True, ext_word_list=None) description = fake.paragraphs(nb=1, ext_word_list=None) sku = fake.msisdn() price = fake.pydecimal(left_digits=None, right_digits=None, positive=True, min_value=0, max_value=None) special_price = fake.pydecimal(left_digits=None, right_digits=None, positive=True, min_value=0, max_value=None) product_type = "Muebles" slug = "mueble-" + str(seed) stock = randint(0, 100) url = json[seed]['download_url'] category = Category.objects.first() if category is None: category = Category(name="Muebles Hogar", description="Categoria de Muebles", slug=slugify("Muebles Hogar")) category.save() product = Product.objects.get_or_create( name=name, summary=summary, description=description, sku=sku, price=price, product_type=product_type, slug=slug, stock=stock, category=category, special_price=special_price, url=url )[0] product.save()
def test_string_representation_book(self): category = Category(name='History') book = Book(category=category, title='The Fire Next Time', author='James Baldwin', publishing_house='Ace Books', price=11.99, release_date=datetime.now(), pages=412) self.assertEqual(str(book), book.title)
def handle(self, *args, **options): print('shop is working!') Category.objects.all().delete() for i in all_ctgr: c = Category() c.name = i c.save() print(c) Product.objects.all().delete() for i in phones: p = Product() p.name = i p.category = c p.save() p.image.save("test.png", File(open('%s/%s' % (MEDIA_ROOT, "icon128.png"), "rb")) ) '''Product.objects.all().delete()
def setUpTestData(cls): #Set up non-modified objects used by all test methods Category.objects.create(name='Картина по номерам', slug='kartina-po-nomeram') Product.objects.create(category=Category(id=1), name='Рассвет', slug='rassvet', price=2000, stock=4) Product.objects.create(category=Category(id=1), name='Закат', slug='zakat', price=1000, stock=40) Product.objects.create(category=Category(id=1), name='Ведьмак', slug='vedmak', price=5000, stock=1)
def get_category(self, url=False, pk=False, page=1): status, response = self.http(url) soup = BeautifulSoup(response, parseOnlyThese=SoupStrainer('div', {'class': 'body clear'})) for a in soup.findAll('a'): href = a['href'] if 'category-r' in href: print href try: src = a.find('img')['src'] img_path = self.get_image(src) except TypeError: img_path = None name = a.find('h4').string try: if pk: p = Category.objects.get(parent_id=pk, name=name) else: p = Category.objects.get(name=name) except Category.DoesNotExist: try: Category.objects.get(slug=slugify(name)) slug = slugify(name) + self.generator(size=4) except Category.DoesNotExist: slug = slugify(name) p = Category(name=name, slug=slug, image=img_path) if pk: p.parent_id = pk p.save() self.get_manufacturer(href, p.pk) self.get_category('%s?ppp=1000&stp=1' % href.replace('?ppp=40&stp=1', ''), p.pk) elif 'products-r' in href and not url in self.category_urls: self.get_product(url, pk) self.category_urls.append(url)
def setUpTestData(cls): #Set up non-modified objects used by all test methods Category.objects.create(name='Картина по номерам', slug='kartina-po-nomeram') Product.objects.create(category=Category(id=1), name='Рассвет', slug='rassvet', price=2000, stock=4) Comments.objects.create(comments_text='bla-bla-bla', comments_product=Product(id=1), author='Nobody')
def create_category(request, category_slug=None): if not request.user.is_authenticated(): return render(request, 'login.html', {'title': 'Login Here'}) else: category = None categories = Category.objects.all() if category_slug: category = get_object_or_404(Category, slug=category_slug) if request.method == 'POST': category = Category() category.name = request.POST['category_name'] category.slug = request.POST['category_slug'] category.save() return render(request, 'create_product.html', {'category': category, 'categories': categories}) return render(request, 'create_category.html', {'category': category, 'categories': categories})
def make_top_categories(): Category.objects.all().delete() get = lambda node_id: Category.objects.get(pk=node_id) root = Category.add_root(name="Catalogue") chinese = root.add_child(name="Chinese") chinese.add_child(name="Drawings") chinese.add_child(name="Ming and Earlier") chinese.add_child(name="Qing Porcelain") chinese.add_child(name="Qing Works of Art") root.add_child(name="Japanese") european = root.add_child(name="European") european.add_child(name="Porcelain") european.add_child(name="Glass") pottery = european.add_child(name="Pottery") pottery.add_child(name="English Pottery") pottery.add_child(name="Italian Pottery") pottery.add_child(name="Spanish Pottery") pottery.add_child(name="French/German Pottery") pottery.add_child(name="Dutch Delft") root.add_child(name="Other") return
def test_string_representation(self): category = Category(name='History') self.assertEqual(str(category), category.name)
def categories_generate(): Category.objects.all().delete() for i in range(1,6): c = Category(code=i,name='Категория ' + str(i)) c.save()
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import django django.setup() from shop.models import Category data = csv.reader(open("C:/Users/Admin/Desktop/sample/enginesearch1/data.csv"),delimiter=",") for row in data: if row[0] != 'number': product = Category() product.id = row[0] product.number = row[0] product.name = row[1] product.slug = row[2] product.created_at = row[3] product.updated_at = row[4] product.rating = row[5] product.url = row[6] product.save()
class TestBookStore(TestCase): """Tests for the bookstore app.""" def setUp(self): self.client = Client() self.category = Category(name="Programming") self.category.save() def tearDown(self): pass def test_non_existing_book_search_by_name(self): """ Test search functionality. Tests retrieval of a non existent book when user enters a book name. """ url = reverse('search') data = { 'name_field': 'Django How to Code' } response = self.client.get(url, data) self.assertEqual(response.status_code, 200) self.assertFalse( '<li>{0}</li>'.format(data.get('name')) in response.content, msg='Search by name should not return a book in the result' ) def test_existing_book_search_by_name(self): """ Test search functionality. Tests retrieval of a book when user enters a book name. """ url = reverse('search') data = { 'name_field': 'Django How to Code' } book = Book(category=self.category, name="Django How to Code") book.save() response = self.client.get(url, data) self.assertEqual(response.status_code, 200) self.assertTrue( '<li>{0}</li>'.format(data.get('name_field')) in response.content, msg='Search by name should return a book in the result' ) def test_existing_book_search_by_category(self): """ Test search functionality. Tests retrieval of a book when user enters a book category. """ url = reverse('search') book_category = 'Programming' book = Book(category=self.category, name="Django How to Code") book.save() data = { 'category_field': book.category.name } response = self.client.get(url, data) self.assertEqual(response.status_code, 200) self.assertTrue( '<li>{0}</li>'.format(book.name) in response.content, msg='Search by category should return a book in the result' ) def test_non_existing_book_search_by_category(self): """ Test search functionality. Tests retrieval of non existent book when user enters a book category. """ url = reverse('search') data = { 'category_field': 'Programming' } response = self.client.get(url, data) self.assertEqual(response.status_code, 200) self.assertFalse( '<li>{0}</li>'.format(data.get('category_field')) in response.content, msg='Search by category should not return a book in the result' )
def setUp(self): self.client = Client() self.category = Category(name="Programming") self.category.save()
def handle(self, *args, **options): for c in ShopCategory.objects.using('old').all().order_by('-parent_id'): category = Category.objects.filter(slug=c.slug).first() if not category: category = Category(pk=c.pk) category.name = c.name category.slug = c.slug category.title = c.title category.description = c.metadesc category.keywords = c.metakey if c.parent_id: parent = Category.objects.filter(pk=c.parent_id).first() if parent: category.parent = parent category.image = c.image category.save() print(category.id)
def test_get_absolute_url_category(self): category = Category(name='History', slug='history') self.assertEqual(category.get_absolute_url(), f'/shop/{category.slug}/')
def handle(self, *args, **options): import os dir_path = os.path.dirname(os.path.realpath(__file__)) print(dir_path) f = open(dir_path + "/data/categories.txt", "r") for x in f: categories = [category.strip() for category in x.split('>')] for n, category in enumerate(categories): if n == 0: if not Category.objects.filter(name=category).exists(): new_category = Category() new_category.name = category new_category.primary = True new_category.save() print(category) else: if not Category.objects.filter(name=category).exists(): parent_category = Category.objects.get(name=categories[n - 1]) new_category = Category() new_category.name = category new_category.parent = parent_category new_category.save() print(category)
def create_item(name="only a test", category=Category(1), price=190_000.0,
from shop.models import Category, Product c1 = Category(name="Mobile Devices") c1.save() c2 = Category(name="Computers") c2.save() p1 = Product( name="Apple iPhone X", price=1149.99, stock=12, description= "iPhone X features a new all-screen design. FaceID, which makes your face your password. And the most powerful and smartest chip ever in a smartphone.", category=c1) p1.save() p2 = Product( name="Google Pixel2", price=860.20, stock=14, description= "The unlocked Pixel 2 provides a clean, bloat-free experience with no unwanted apps, one of the highest rated smartphone cameras, with free unlimited storage.", category=c1) p2.save() p3 = Product( name="Sony Xperia ZX2", price=920.49, stock=9, description= "The Xperia XZ2 is packed with the latest Sony technologies to deliver an entertainment experience that touches your senses in a whole new way – whether you’re lost in a HDR movie or capturing hidden details with the new advanced Motion Eye™ camera.", category=c1) p3.save() p4 = Product( name="Dell Inspiron 175000",
def generate_products(self, request): #제조 회사 데이터 정의 maker1 = Maker(name="모바일 메이커1") maker2 = Maker(name="기타 메이커2") #제품 분류 정의 root_electric = Category( name = "전자제품" ) middle_mobile = Category( name = "모바일", parent = root_electric ) middle_etc = Category( name = "기타", parent = root_electric ) middle_onsale = Category( name = "세일", parent = root_electric ) leaf_smartphone = Category( name = "스마트폰", parent = middle_mobile ) leaf_tablet = Category( name = "태블릿", parent = middle_mobile ) leaf_notebook = Category( name = "노트북", parent = root_electric ) #제품 데이터 정의 p1 = self.generate_product("스마트폰1", maker1) pc1 = ProductCategory( category=leaf_smartphone, product=p1 ) pi1 = ProductImage( photo_url = "images/products/product_1.jpg", product = p1 ) p2 = self.generate_product("음향기기1", maker2) pc2 = ProductCategory( category=middle_etc, product=p2 ) pi2 = ProductImage( photo_url = "images/products/product_2.jpg", product = p2 ) p3 = self.generate_product("악세사리1", maker2) pc3 = ProductCategory( category=middle_etc, product=p3 ) pi3 = ProductImage( photo_url = "images/products/product_3.jpg", product = p3 ) p4 = self.generate_product("노트북1", maker1) pc4 = ProductCategory( category=leaf_notebook, product=p4 ) pi4 = ProductImage( photo_url = "images/products/product_4.jpg", product = p4 ) p5 = self.generate_product("헤드폰1", maker2) pc5 = ProductCategory( category=middle_etc, product=p5 ) pi5 = ProductImage( photo_url = "images/products/product_5.jpg", product = p5 ) p6 = self.generate_product("태블릿1", maker1) pc6 = ProductCategory( category=leaf_tablet, product=p6 ) pi6 = ProductImage( photo_url = "images/products/product_6.jpg", product = p6 ) p7 = self.generate_product("스마트폰2", maker1) pc7 = ProductCategory( category=leaf_smartphone, product=p7 ) pi7 = ProductImage( photo_url = "images/products/product_7.jpg", product = p7 ) p8 = self.generate_product("키보드1", maker2) pc8 = ProductCategory( category=middle_etc, product=p8 ) pi8 = ProductImage( photo_url = "images/products/product_8.jpg", product = p8 ) p9 = self.generate_product("드론1", maker2) pc9 = ProductCategory( category=middle_etc, product=p9 ) pi9 = ProductImage( photo_url = "images/products/product_9.jpg", product = p9 ) p10 = self.generate_product("헤드폰2", maker2) pc10 = ProductCategory( category=middle_etc, product=p10 ) pi10 = ProductImage( photo_url = "images/products/product_10.jpg", product = p10 ) p11 = self.generate_product("게임콘솔1", maker2) pc11 = ProductCategory( category=middle_etc, product=p11 ) pi11 = ProductImage( photo_url = "images/products/product_11.jpg", product = p11 ) p12 = self.generate_product("렌즈1", maker2) pc12 = ProductCategory( category=middle_etc, product=p12 ) pi12 = ProductImage( photo_url = "images/products/product_12.jpg", product = p12 ) makers = [maker1, maker2] for m in makers: #이름이 중복되는 제조 회사가 없다면 추가 if Maker.objects.filter(name=m.name).first() is None: m.save() categories = [ root_electric, middle_mobile, middle_etc, middle_onsale, leaf_notebook, leaf_smartphone, leaf_tablet ] for c in categories: if Category.objects.filter(name=c.name).first() is None: c.save() products = [ p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12 ] addedProductCount = 0 for p in products: #이름이 중복되는 제품이 없다면 추가 if Product.objects.filter(name=p.name).first() is None: p.save() addedProductCount += 1 if addedProductCount == 12: productCategories = [ pc1, pc2, pc3, pc4, pc5, pc6, pc7, pc8, pc9, pc10, pc11, pc12 ] for pc in productCategories: pc.save() productImages = [ pi1, pi2, pi3, pi4, pi5, pi6, pi7, pi8, pi9, pi10, pi11, pi12 ] for pi in productImages: pi.save() return Response({ 'appliedCount': addedProductCount })
def create(self, validated_data): category = Category(**validated_data) category.save() return category
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) a, b, c, d, e = Category.find_problems() context["errors"] = a or b or c or d or e return context
def UpLoadDataFromCsv(path=mypath): writeCsvFiles(path) with open('list.csv', 'rb') as csvfile: rows = csv.DictReader(x.replace('', '') for x in csvfile) for row in rows: try: Navbar.objects.get(name=row['navbar']) try: category = Category.objects.get(name=row['category']) try: Product.objects.get(name=row['name']) continue except Product.DoesNotExist: product = Product(category=category, name=row['name'], kilometers=row['kilometers'], price=row['price'], stock=['stock'], available=row['available']) name = row['name'] dir = row['directory'] product.image = ImageFile(open(dir, 'rb')) product.save() #product.image.save(File(open(dir,'rb'))) #product.image.save(name,File(open(dir,'r'))) #image = ImageFile(open("".join(row['directory']),"r")) #product = Product(category=category,name=row['name'],image=image,kilometers=row['kilometers'],price=row['price'],stock=['stock'],available=row['available']) #product = Product(category=category,name=row['name'],kilometers=row['kilometers'],price=row['price'],stock=['stock'],available=row['available']) #product.image = ImageFile(open("".join(row['directory']),"r")) #product.image = "products/".join(row['directory']) #product.save() except Category.DoesNotExist: category = Category(navbar=nav, name=row['category']) category.save() product = Product(category=category, name=row['name'], kilometers=row['kilometers'], price=row['price'], stock=['stock'], available=row['available']) name = row['name'] dir = row['directory'] product.image.save(name, File(open(dir, 'rb'))) #product.image.save(row['name'].join('.jpg'),File(open(row['directory'],'r'))) #product = Product(category=category,name=row['name'],kilometers=row['kilometers'],price=row['price'],stock=['stock'],available=row['available']) #product.image = ImageFile(open("".join(row['directory']),"r")) #product.image = "products/".join(row['directory']) #product.save() except Navbar.DoesNotExist: nav = Navbar(name=row['navbar']) nav.save() #createProduct(nav,row['category']) category = Category(navbar=nav, name=row['category']) category.save() name = row['name'] dir = row['directory'] product = Product(category=category, name=row['name'], kilometers=row['kilometers'], price=row['price'], stock=['stock'], available=row['available']) product.image.save(name, File(open(dir, 'rb'))) #product.image.save(row['name'].join('.jpg'),File(open(row['directory'],'r'))) #product = Product(category=category,name=row['name'],kilometers=row['kilometers'],price=row['price'],stock=['stock'],available=row['available']) #product.image = ImageFile(open("".join(row['directory']),"r")) #product.image = "products/".join(row['directory']) #product.save() csvfile.close()