def add_category(request, letter, name): try: category = Category.objects.get(letter=letter) except Category.DoesNotExist: category = None if category is not None: return simplejson.dumps({ 'result': False, 'message': 'A category with this letter already exists.' }) try: category = Category.objects.get(name=name) except Category.DoesNotExist: category = None if category is not None: return simplejson.dumps({ 'result': False, 'message': 'A category with this name already exists.' }) if len(letter) > 2: return simplejson.dumps( { 'result': False, 'message': 'Letter field can only be two characters.' }) category = Category(letter=letter, name=name) category.save() return simplejson.dumps({ 'result': True })
def go_items(xmldoc, log): itemslist = xmldoc.getElementsByTagName(u'Товар') Item.objects.all().delete() for i in itemslist: id = i.attributes[u'Идентификатор'].value name = i.attributes[u'Наименование'].value parent_id = i.attributes[u'Родитель'].value # категория desc_list = xmldoc.getElementsByTagName(u'ЗначениеСвойства') description = '' description_bottom = '' for d in desc_list: if d.attributes[u'ИдентификаторСвойства'].value == u'ПолноеНаименование': description = d.attributes[u'Значение'].value elif d.attributes[u'ИдентификаторСвойства'].value == u'Комментарий': description_bottom = d.attributes[u'Значение'].value if Category.has_id_1c(parent_id): Item(name=name, category=Category.get_by_id_1c(parent_id), id_1c=id, art=id, price=0, description=description, description_bottom=description_bottom).save() else: log.append(u'Не загружен товар с идентификатором %s. Нет родительской категории %s.'% (id, parent_id)) log.append(u'Товары загружены успешно.')
def handle(self, *fixture_labels, **options): if len(fixture_labels) > 0: path = fixture_labels[0] if not os.path.exists(path): print "Path does not exist:", path return fields = fields_for_model(Category) reader = csv.reader(open(path), delimiter=";") self.header = reader.next() columns = list(set(fields.keys()) & set(self.header)) if "id" in self.header: key = "id" elif "slug" in self.header: key = "slug" else: raise ValueError("Either id or slug column must be present in csv data.") for row in reader: pk = self.get_value(key, row) q = {key: pk} data = dict([(c, getattr(self, "resolve_" + c, self.get_value)(c, row)) for c in columns]) cat = None if Category.objects.filter(**q).count() > 0: Category.objects.filter(**q).update(**data) cat = Category.objects.get(**q) else: if key not in data: data[key] = pk cat = Category(**data) if cat: cat.save()
def new_category(name): """ new_category creates a new Category object given the name """ category = Category() category.name = name return category
def test_category_categoryname_model(): gongfu = Brewing( temperature=99, weight=5, initial=timedelta(seconds=10), increments=timedelta(seconds=3), ) gongfu.save() western = Brewing( temperature=85, weight=0.8, initial=timedelta(seconds=180), increments=timedelta(seconds=30), ) western.save() category = Category(name="OOLONG", gongfu_brewing=gongfu, western_brewing=western) category.save() assert category.name == "OOLONG" assert str(category.gongfu_brewing) == "5g 99°c 10s +3s" assert type(category.western_brewing) == Brewing categoryname = CategoryName(category=category, name="blue") categoryname.save() assert categoryname.name == "blue"
def category_subcategory_add(request, category_id): categories = Category.objects.all().order_by('name') category = Category() category.main_category = get_object_or_404(Category, pk=category_id) context = { 'category': category, 'categories': categories, } return render(request, 'category_add.html', context)
def test_create_category(self): nbr_of_category_before_add = Category.objects.count() new_category = Category() new_category.name = "Moins de gras" new_category.save() nbr_of_category_after_add = Category.objects.count() self.assertTrue(nbr_of_category_after_add == nbr_of_category_before_add + 1)
def test_valid_subcategory_serializer(client): user = CustomUser(email="*****@*****.**") user.save() category = Category(name="OOLONG") category.save() valid_serializer_data = { "user": user, "name": "test", "category": category.id } serializer = SubcategorySerializer(data=valid_serializer_data) assert serializer.is_valid() assert type(serializer.validated_data["category"]) == Category assert serializer.errors == {}
def handle(self, *args, **options): print 'Start loading categories' Category.objects.all().delete() SubCategory.objects.all().delete() categories = self.parse() for i in categories: c = Category(name=i['name']) c.save() for j in i['sub_cat']: s = SubCategory(name=j['name'], parent_category=c) s.save() for h in j['sub']: _s = SubSubCategory(name=h, parent_sub_category=s) _s.save() print 'Process ... %s' % s.name
def newCategory(): """ Create new category """ # user must be authenticated if 'user_id' not in session: return redirect('/login') form = CategoryForm() if form.validate_on_submit(): # check that name != 'new', which is used for routing if form.name.data.lower() == 'new': form.name.errors.append("'new' is a reserved word, and cannot" " be used as a category name.") return render_template('new_category.html', form=form) category = Category(name=form.name.data, user_id=session['user_id']) db_session.add(category) try: db_session.commit() except exc.IntegrityError: # category name should be unique db_session.rollback() form.name.errors.append("Category already exists.") return render_template('new_category.html', form=form) flash("Created new category %s." % category.name) return redirect(url_for('catalog')) return render_template('new_category.html', form=form)
def category_filter(request, slug): c = get_common_context(request) if 'category' in request.POST: slug = request.POST['category'] if slug: c['category'] = Category.get_by_slug(slug) items = Item.objects.filter(category__in=c['category'].get_descendants(include_self=True)) for k in request.POST.keys(): if k.startswith('parametr_'): p_id = k[9:] p_value = request.POST[k] if p_id == 'price_from' and p_value: items = items.filter(price__gte=float(p_value)) c['price_from'] = int(p_value) elif p_id == 'price_to' and p_value: items = items.filter(price__lte=float(p_value)) c['price_to'] = int(p_value) else: items = Item.filter_by_parametr(items, p_id, p_value) else: items = Item.objects.all() if 'q' in request.POST: items = items.filter(name__icontains=request.POST['q']) c['items'] = items return render_to_response('catalog.html', c, context_instance=RequestContext(request))
def set_base_data(request): context = { 'settings': settings, } path = request.path excluded = ( '/%s' % settings.ADMIN_URL, '/%s/' % settings.API_URL.strip('/'), ) if path.startswith(excluded): return context get_array_item_by_name = lambda name, collection: [item for item in collection if item.name == name] get_first = lambda collection: first(collection) if len(collection) else None get_by_name = lambda name, collection: get_first(get_array_item_by_name(name, collection)) section_main = Section.get_main() context.update({ 'host': settings.SITE_HOST, 'config': globals.config, 'category_product': list(Category.get_main()), 'top_menu': section_main, 'catalog_section': globals.catalog, 'cart_section': get_by_name('shopping-cart', section_main), }) return context
class BoxNameTest(unittest.TestCase): def setUp(self): self.cat = Category(letter="C", name="Mother and Child") self.cat.save() self.data = BoxName.objects.create(category=self.cat, name="Data") def test_box_name_export(self): test = self.data csv = test.to_csv() self.assertTrue(csv=="C,Data") #fix def test_box_name_import(self): data = "C,Test" csv = BoxName.create_from_csv(data) self.assertTrue(BoxName.objects.get(name="Test") is not None)
def category(node: Category): return { "name": node.name, "id": node.id, "children": list(map(category, node.get_children())), "courses": list(map(course, node.course_set.all())), }
def newCategory(): if request.method == 'GET': return render_template('new_category.html') elif request.method == 'POST': try: if request.form['name']: newCategory = Category(name=request.form['name'], user_id=current_user.id) db.session.add(newCategory) db.session.commit() flash({ "message": "Category successfully added!", "role": "success" }) else: flash({ "message": "Category name cannot be empty!", "role": "failure" }) return redirect(url_for('main.showHome')) except exc.SQLAlchemyError as e: flash({ "message": "Something went wrong while processing your request.", "role": "failure" }) return redirect('/')
def seed(): """Create some default categories""" # Seed some default categories categories = [ { 'name': 'Backend' }, { 'name': 'Frontend' }, { 'name': 'DevOps' }, { 'name': 'QA' }, { 'name': 'Data Science' }, { 'name': 'BlockChain' }, ] for category in categories: new_category = Category(name=category['name']) db.session.add(new_category) db.session.commit()
def test_user_can_create_and_view_subcategory(client, token): category = Category(name="OOLONG") category.save() resp = client.post( "/api/subcategory/", {"name": "Test", "translated_name": "Still test", "category": category.id}, content_type="application/json", HTTP_AUTHORIZATION=f"Bearer {token}", ) assert resp.status_code == 201 resp = client.get("/api/subcategory/", HTTP_AUTHORIZATION=f"Bearer {token}") assert resp.status_code == 200 assert resp.data[0]["user"] assert resp.data[0]["name"] == "Test" assert resp.data[0]["translated_name"] == "Still test" assert resp.data[0]["category"] == category.id
def seed_db(): user1 = User(name='user1', email='*****@*****.**') user2 = User(name='user2', email='*****@*****.**') db.session.add(user1) db.session.add(user2) db.session.commit() categories_data = [ {'name': 'Football'}, {'name': 'Tennis'}, ] for categories in categories_data: new_category = Category(name=categories['name']) db.session.add(new_category) db.session.commit() items_data = [ {'name': 'Ball', 'description': 'Football', 'category_id': 1}, {'name': 'Net', 'description': 'Football', 'category_id': 1}, {'name': 'Racket', 'description': 'Tennis', 'category_id': 2}, {'name': 'Tennis ball', 'description': 'Football', 'category_id': 2}, ] for index, item in enumerate(items_data): new_item = Item(name=item['name'], description=item['description'], category_id=item['category_id'], user_id=(index % 2 + 1)) db.session.add(new_item) db.session.commit()
def task_category(self, grab, task): print "Category url: %s" % task.url cats = Category.objects.filter(urls__contains=task.url) if not cats: cat = Category(name=task.elem.text.strip(), root_category=task.get("category")) cat.urls = task.url cat.save() else: cat = cats[0] if task.elem.getnext(): for elem in task.elem.getnext().xpath(".//a"): if elem.getnext(): continue yield Task('category', url="".join((elem.get("href"),"?ALL=1")), elem=elem, category=cat) else: for elem in grab.doc.select(self.xpath['product']): yield Task('product', url=elem.attr("href"), category=cat)
def test_user_can_create_and_view_vendor(client, token): category = Category(name="OOLONG") category.save() resp = client.post( "/api/vendor/", {"name": "Test", "website": "https://www.stilltest.com", "popularity": 7}, content_type="application/json", HTTP_AUTHORIZATION=f"Bearer {token}", ) assert resp.status_code == 201 resp = client.get("/api/vendor/", HTTP_AUTHORIZATION=f"Bearer {token}") assert resp.status_code == 200 assert resp.data[0]["user"] assert resp.data[0]["name"] == "Test" assert resp.data[0]["website"] == "https://www.stilltest.com" assert resp.data[0]["popularity"] == 7
def get_context_data(self, **kwargs): return { 'seo': views.get_seo(), 'banner_products': Product.get_banner(), 'other_products': Product.get_other(), 'other_stock': Category.get_other(), }
def test_tea_nested_serializers_create_update(client, token): category = Category(name="OOLONG") category.save() resp_vendor = client.post( "/api/vendor/", { "name": "Test vendor", "website": "https://www.stilltest.com", "popularity": 7, }, content_type="application/json", HTTP_AUTHORIZATION=f"Bearer {token}", ) assert resp_vendor.status_code == 201 resp_post = client.post( "/api/tea/", { "name": "Test tea", "subcategory": {"name": "Test subcategory", "category": category.id}, "vendor": {"name": "Test vendor"}, }, content_type="application/json", HTTP_AUTHORIZATION=f"Bearer {token}", ) assert resp_post.status_code == 201 assert resp_post.data["name"] == "Test tea" assert resp_post.data["subcategory"]["name"] == "Test subcategory" assert resp_post.data["vendor"]["name"] == "Test vendor" assert resp_post.data["vendor"]["id"] == resp_vendor.data["id"] _id = resp_post.data["id"] resp_put = client.put( f"/api/tea/{_id}/", { "name": "Updated tea", "subcategory": {"name": "Updated subcategory", "category": category.id}, "vendor": {"name": "Test vendor"}, }, content_type="application/json", HTTP_AUTHORIZATION=f"Bearer {token}", ) assert resp_put.status_code == 200 assert resp_put.data["name"] == "Updated tea" assert resp_put.data["subcategory"]["name"] == "Updated subcategory" assert resp_put.data["subcategory"]["id"] != resp_post.data["subcategory"]["id"] assert resp_put.data["vendor"]["name"] == "Test vendor" assert resp_put.data["vendor"]["id"] == resp_post.data["vendor"]["id"]
def test_subcategory_subcategoryname_model(): user = CustomUser(email="*****@*****.**") user.save() category = Category(name="OOLONG") category.save() origin = Origin(country="Germany", region="Yunnan", locality="Paris", user=user) origin.save() gongfu = Brewing( temperature=99, weight=5, initial=timedelta(seconds=10), increments=timedelta(seconds=3), ) gongfu.save() western = Brewing( temperature=85, weight=0.8, initial=timedelta(seconds=180), increments=timedelta(seconds=30), ) western.save() subcategory = Subcategory( category=category, name="Da Hong Pao", translated_name="Big Red Robe", origin=origin, user=user, gongfu_brewing=gongfu, western_brewing=western, ) subcategory.save() assert not subcategory.is_public assert subcategory.name == "Da Hong Pao" assert subcategory.category.name == "OOLONG" assert subcategory.translated_name == "Big Red Robe" assert subcategory.origin.locality == "Paris" assert subcategory.gongfu_brewing.temperature == 99 assert subcategory.western_brewing.weight == 0.8 assert str(subcategory) == "Da Hong Pao (Big Red Robe)" subcategoryname = SubcategoryName(subcategory=subcategory, name="dhp") subcategoryname.save() assert subcategoryname.name == "dhp"
def handle(self, *args, **options): print('Loading category') Category.objects.all().delete() Journal.objects.all().delete() names = ['ЖЕНСКИЕ', 'МУЖСКИЕ', 'ДЕТСКИЕ', 'ДОМ И СЕМЬЯ'] cntc = 0 for name in names: cntc += 1 c = Category() c.name = name c.save() print('Saving %s' % name) journal_list = ['Наука и техника', 'Здоровье', 'Моделист-конструктор', 'Лиза', 'Прибой', 'Забой', 'Внуки и правнуки', 'В мире муравья'] cnt = 0 for jname in journal_list: cnt += 1 j = Journal() j.name = jname+" "+str(cnt)+str(cntc) j.is_public = True j.show_in_books = True j.is_popular = True j.save() j.category.add(c) path = os.path.join(settings.BASE_DIR,'init_data','journal',f'{cnt}.jpg') with open(path, 'rb') as doc_file: j.default_cover.save(f'{cnt}.jpeg', File(doc_file), save=True) for ni in range(1,20): name = f'выпуск {ni}' i = Issue() i.name = name i.is_public = True i.journal = j i.save() for pi in range(1,10): p = IssuePage() p.paper = i p.page = pi p.save() path = os.path.join(settings.BASE_DIR,'init_data','journal',f'{pi}.jpg') with open(path, 'rb') as doc_file: p.file_low.save(f'{pi}.jpeg', File(doc_file), save=True) p.file_middle.save(f'{pi}.jpeg', File(doc_file), save=True) p.file_high.save(f'{pi}.jpeg', File(doc_file), save=True)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) categories = Category.get_categories_with_dishes() order = Order.get_current_temp_order(self.request.session) context['current_category'] = self.category context['categories'] = categories context['order'] = order return context
def category_create(): """ This creates a new category only if the user is logged in """ if not logged_in(): flash('Please log in to create categories') return redirect(url_for('category_list')) form = CategoryForm() if form.validate_on_submit(): category = Category() category.title = form.title.data user = get_current_user() category.ctlg_user = user db.session.add(category) db.session.commit() return redirect(url_for('category_list')) return render_template('category_create.html', form=form)
def handle(self, *args, **options): print 'Start loading categories' Category.objects.all().delete() SubCategory.objects.all().delete() categories = json.load( open(os.path.join(BASE_DIR, 'data', 'categories.json')))['result'] for i in categories: c = Category(name=i['name']) c.save() for j in i['sub_cat']: s = SubCategory(name=j['name'], parent_category=c) s.save() for h in j['sub']: _s = SubSubCategory(name=h, parent_sub_category=s) _s.save() print 'Process ... %s' % s.name cache.delete('categories')
def catalog_view(request): products = Product.objects.all() stop_price = 0 for product in products: if product.sale_status and product.price_sale > stop_price: stop_price = product.price_sale elif product.price > stop_price: stop_price = product.price categ = Category() categ.name = "Каталог" return render_to_response("category.html", { 'categ': categ, 'products': products, 'stop_price': stop_price, 'collections': Collection.objects.all(), })
def get_common_context(request): c = {} c['request_url'] = request.path c['is_debug'] = settings.DEBUG c['categories'] = Category.get_top() c['cart_working'] = SessionCartWorking(request) c['cart_count'], c['cart_sum'] = c['cart_working'].get_goods_count_and_sum() c.update(csrf(request)) return c
def search(request): c = get_common_context(request) if request.method == 'POST': q = request.POST.get('q', '') if q: c['q'] = q c['s_categories'] = Category.search(q) c['s_items'] = Item.search(q) return render_to_response('search_res.html', c, context_instance=RequestContext(request)) return HttpResponseRedirect('/')
def category(request, slug): c = get_common_context(request) if slug: c['category'] = Category.get_by_slug(slug) items = Item.objects.filter(category__in=c['category'].get_descendants(include_self=True)) else: items = Item.objects.all() c['items'] = items return render_to_response('catalog.html', c, context_instance=RequestContext(request))
def test_brewing_session_model(): user = CustomUser(email="*****@*****.**") user.save() category = Category(name="OOLONG") category.save() tea = Tea(user=user, name="Da Hong Pao") tea.save() brewing = Brewing( temperature=99, weight=5, initial=timedelta(seconds=10), increments=timedelta(seconds=3), ) brewing.save() session = BrewingSession(user=user, tea=tea, brewing=brewing) session.save() assert session.user.email == "*****@*****.**" assert session.tea.name == "Da Hong Pao" assert session.brewing.temperature == 99 assert session.current_infusion == 1 assert not session.is_completed assert session.created_on
def add(request): if request.method == 'POST': form = FormCategory(request.POST) if form.is_valid(): category = Category() category.name = request.POST['name'] category.save() messages.success(request, 'Record saved successfully!') return redirect('/category/') else: messages.warning(request, 'Erro occurred! Try again!') return redirect('/category/') else: form = FormCategory() return render(request, 'category/add.html', { 'form':form })
def handle(self, *args, **kwargs): services = [ ('查经', 'Bible Study', '创世纪1', '2020-07-20'), ('查经', 'Bible Study', '创世纪2', '2020-07-25'), ('查经', 'Bible Study', '创世纪3', '2020-07-31'), ('敬拜', 'Worship', '新心音乐', '2020-07-20'), ('敬拜', 'Worship', '赞美之泉', '2020-07-25'), ('敬拜', 'Worship', 'Hillsong', '2020-07-31'), ('饭食', 'Food pickup', 'First Chinese', '2020-07-20'), ('饭食', 'Food pickup', 'Panda Express', '2020-07-25'), ('饭食', 'Food pickup', 'Chickfila', '2020-07-31'), ] kcat, kds, kdt, knt = kwargs.get('category'), kwargs.get( 'description'), kwargs.get('date'), kwargs.get('note') # Create several services if not kcat and not kds and not kdt and not knt: for ser in services: cat = Category.objects.filter(name=ser[0]).first() if not cat: # Create the category cat = Category(name=ser[0]) cat.save() s = Service( description=ser[1], note=ser[2], service_date=str2date(ser[-1]), ) s.save() s.categories.add(cat) # todo: create services of the week self.stdout.write('Service records are saved successfully.') else: # Create a service cat = Category.objects.filter(name=kwargs.get('category')).first() if not cat: cat = Category(name=kwargs.get('category')) cat.save() sr = Service(service_date=str2date(kwargs.get('date')), description=kwargs.get('description'), note=kwargs.get('note')) sr.save() sr.categories.add(cat) self.stdout.write('Service record is saved successfully.')
def handle(self, *fixture_labels, **options): if len(fixture_labels) > 0: path = fixture_labels[0] if not os.path.exists(path): print 'Path does not exist:', path return fields = fields_for_model(Category) reader = csv.reader(open(path), delimiter=";") self.header = reader.next() columns = list(set(fields.keys()) & set(self.header)) if 'id' in self.header: key = 'id' elif 'slug' in self.header: key = 'slug' else: raise ValueError( 'Either id or slug column must be present in csv data.') for row in reader: pk = self.get_value(key, row) q = {key: pk} data = dict([(c, getattr(self, 'resolve_' + c, self.get_value)(c, row)) for c in columns]) cat = None if Category.objects.filter(**q).count() > 0: Category.objects.filter(**q).update(**data) cat = Category.objects.get(**q) else: if key not in data: data[key] = pk cat = Category(**data) if cat: cat.save()
def catalog_page(request): c = get_common_context(request) if request.method == "POST": if request.POST["action"] == "add_in_basket": c["cart_working"].add_to_cart(request.user, request.POST["item_id"]) messages.success(request, u"Товар был добавлен в корзину.") return HttpResponseRedirect(request.get_full_path()) car_model = int(request.GET.get("car_model", "0")) category = int(request.GET.get("category", "0")) color = int(request.GET.get("color", "0")) search = request.GET.get("search", "") items = Item.objects.all() if car_model: items = items.filter(car_model=car_model) c["car_model_name"] = CarModel.get_name(car_model) if color: items = items.filter(color=color) if category: items = items.filter(category=category) c["category_name"] = Category.get_name(category) if search: items = items.filter(name__icontains=search) c["car_model"] = car_model c["color"] = color c["category"] = category c["search"] = search c["get_request"] = c["request_url"] + "?car_model=%s&category=%s&color=%s&search=%s" % ( car_model, category, color, search, ) paginator = Paginator(items, 15) page = int(request.GET.get("page", "1")) try: c["items"] = paginator.page(page) except PageNotAnInteger: page = 1 c["items"] = paginator.page(page) except EmptyPage: page = paginator.num_pages c["items"] = paginator.page(page) c["page"] = page c["page_range"] = paginator.page_range if len(c["page_range"]) > 1: c["need_pagination"] = True return render_to_response("catalog.html", c, context_instance=RequestContext(request))
def go_categories(xmldoc, log): categorieslist = xmldoc.getElementsByTagName(u'Группа') Category.objects.all().delete() cicle = True while cicle: count_a = Category.objects.all().count() for s in categorieslist: id = s.attributes[u'Идентификатор'].value name = s.attributes[u'Наименование'].value try: parent_id = s.attributes[u'Родитель'].value except: parent_id = None if (parent_id is None) or Category.has_id_1c(parent_id): if not Category.has_id_1c(id): Category(name=name, parent=Category.get_by_id_1c(parent_id), id_1c=id).save() else: pass #print 'NOTSAVED: %s - %s - %s' % (id, name, parent_id) cicle = Category.objects.all().count() > count_a log.append(u'Категории загружены успешно.')
def category(request, slug): c = get_common_context(request) if slug: c['category'] = Category.get_by_slug(slug) c['title'] = c['category'].name items = Item.objects.filter(category__in=c['category'].get_descendants(include_self=True), hidden=False) if c['category'].parent: c['subcategories'] = c['category'].parent.get_descendants().extra(order_by = ['id']) else: c['subcategories'] = c['category'].get_descendants().extra(order_by = ['id']) else: items = Item.objects.all() c['subcategories'] = Category.objects.filter(parent=None) c['title'] = u'Каталог' return render_to_response('category.html', filter_items(request, c, items), context_instance=RequestContext(request))
def toggle_category(): resp = {'status': 'success'} urlkey = request.args.get('key') if urlkey is None: raise tasklets.Return({'status': 'error'}) category = yield Category.get_async(urlkey) u2c = yield User2Category.delete_async(g.user, category) if u2c: resp.update({'data': 'deleted'}) elif category is not None: User2Category.create_async(g.user, category) resp.update({'data': 'created'}) else: resp['status'] = 'error' raise tasklets.Return(request.is_xhr and jsonify(**resp) or redirect(url_for('.setup_profile')))
def __init__(self, *args, **kwargs): super(CatalogBaseView, self).__init__(*args, **kwargs) self.categories = Category.get_categories() self.publishers = Publisher.get_publishers() self.currencies = Currency.get_currencies() self.primary_currency = next((currency for currency in self.currencies if currency.is_primary), None) if self.primary_currency is None: raise ImproperlyConfigured('No primary currency is defined for ideapub.' ' You should defined primary currency for the system with exchange rate of 1.' ' All prices & costs should be defined in primary currency value.') if self.primary_currency.exchange_rate != 1: raise ImproperlyConfigured('Primary currency should have exchange rate of 1.' ' All prices & costs should be defined in primary currency value.')
def category(request, slug): c = get_common_context(request) c['category'] = Category.get_by_slug(slug) if not c['category']: return page_page(request, slug) page = c['category'] breadcrumbs = [] while page: breadcrumbs.append(page) page = page.parent breadcrumbs.reverse() c['titles'] = breadcrumbs[:-1] c['items'] = Item.objects.filter(category=c['category']) if len(c['items']) == 0: c['items'] = Item.objects.filter(category__in=c['category'].get_descendants(include_self=True)) return render_to_response('category.html', c, context_instance=RequestContext(request))
def category(request, slug): c = get_common_context(request) if slug: c['category'] = Category.get_by_slug(slug) items = Item.objects.filter(category__in=c['category'].get_descendants(include_self=True)) else: items = Item.objects.all() c['brands'] = [] c['colors'] = [] c['materials'] = [] for i in items: if i.brand and i.brand not in c['brands']: c['brands'].append(i.brand) if i.color and i.color not in c['colors']: c['colors'].append(i.color) if i.material and i.material not in c['materials']: c['materials'].append(i.material) return render_to_response('category.html', filter_items(request, c, items), context_instance=RequestContext(request))
def edit(item_id): item = Item.query.filter_by(id=item_id).first_or_404() form = ItemForm(obj=item) print(form) if form.validate_on_submit(): form.populate_obj(item) print(form.validate_on_submit()) if form.new_category.data: new_category = Category(form.new_category.data) db.session.add(new_category) db.session.flush() post.category = new_category db.session.commit() return redirect(url_for('article', slug=item.slug)) return render_template('catalog/items.html', form=form, item=item, action="edit")
def index(): """ Get categories. rtype: dict """ db_categories = Category.all() categories = list() for x in db_categories: categories.append({ 'id': x.hash_id, 'name': x.name, 'url_safe_name': "_".join(x.name.split(' ')) }) return categories
def new_category(): """ Function to create a new category. """ set_redirect_url() user = get_user() if not user: return redirect(url_for('login')) if request.method == 'POST': category = Category(name=request.form['name'], user_id=login_session['user_id']) db_session.add(category) db_session.commit() flash('New Category {} Successfully Created!'.format(category.name)) return redirect(url_for('index')) else: return render_template('new_category.html', user=user)
def run(request): categories = Category.get_categories_with_dishes() dishes = Dish.objects.filter(is_draft=False) order = Order.get_current_temp_order(request.session) if order: for dish in dishes: dish_in_order = order.order_dish.filter(dish=dish).first() if dish_in_order: dish.count = dish_in_order.count return render(request, 'catalog/index.html', context={ 'categories': categories, 'dishes': dishes, 'order': order })
def __init__(self, *args, **kwargs): super(CatalogBaseView, self).__init__(*args, **kwargs) # Loading categories self.categories = Category.get_categories() self.manufacturers = Manufacturer.get_manufacturers() self.currencies = Currency.get_currencies() self.primary_currency = next( (currency for currency in self.currencies if currency.is_primary), None) if self.primary_currency is None: raise ImproperlyConfigured( 'No primary currency is defined for Doorsale.' ' You should defined primary currency for the system with exchange rate of 1.' ' All prices & costs should be defined in primary currency value.' ) if self.primary_currency.exchange_rate != 1: raise ImproperlyConfigured( 'Primary currency should have exchange rate of 1.' ' All prices & costs should be defined in primary currency value.' )
def items(): form = ItemForm() if form.validate_on_submit(): if form.new_category.data: new_category = Category(form.new_category.data) db.session.add(new_category) db.session.flush() category = new_category elif form.category.data: category_id = form.category.get_pk(form.category.data) category = Category.query.filter_by(id=category_id).first() else: category = None catalog = Catalog.query.first() author = Author.query.filter_by(username=session['username']).first() title = form.title.data description = form.description.data slug = slugify(title) item = Item(catalog, author, title, description, category, slug) db.session.add(item) db.session.commit() return redirect(url_for('article', slug=slug)) return render_template('catalog/items.html', form=form, action="new")
def category_save(request, category_id): categories = Category.objects.all().order_by('name') error = False error_message = [] if(category_id == 0 or category_id == '0'): category = Category() else: category = get_object_or_404(Category, pk=category_id) category.name = request.POST['name'] category.description = request.POST['description'] if len(category.name) == 0: error = True error_message.append("Name is required") main_category = request.POST['main_category'] if main_category != 0 and main_category != '0': category.main_category = Category.objects.get(id=main_category) else: category.main_category = None if error: context = { 'category': category, 'error_message': error_message, 'categories': categories, } return render(request, 'category_add.html', context) else: category.save() context = { 'categories': categories, 'category': category, 'success_message': 'La categoria ' + category.name + ' ha sido guardada exitosamente.', } return render(request, 'category.html', context)
def add_item(category, item): item.category_id = category.id db.add(item) db.commit() user = User(name="Peter Pan", email="*****@*****.**", picture="https://placehold.it/300x300.png?text=Peter+Pan") db.add(user) db.commit() category1 = Category(name="Books") db.add(category1) category2 = Category(name="Electronics") db.add(category2) category3 = Category(name="Food") db.add(category3) category4 = Category(name="Miscellaneous") db.add(category4) db.commit() add_item( category1,
def setUp(self): c = Category(name='Test category') c.save()
def initdb(): from catalog.models import User, Category, Course user1 = User(name='Seunghun Lee', email='*****@*****.**') db.session.add(user1) db.session.commit() categories = [ 'Programming Language', 'Math', 'Physics', 'Deep Learning', ] # Add Categories for category_name in categories: new_category = Category(name=category_name, user_id=1) db.session.add(new_category) db.session.flush() course = Course(name='Programming Foundations with Python', level='Beginner', url='https://www.udacity.com/course/programming-foundations-with-python--ud036', image_url='https://s3-us-west-1.amazonaws.com/udacity-content/course/images/ud036-0619766.jpg', description='Learn Object-Oriented Programming', provider='Udacity', category_id=1, user_id=1) db.session.add(course) course = Course(name='Linear Algebra Refresher Course', level='Intermediate', url='https://www.udacity.com/course/linear-algebra-refresher-course--ud953', image_url='https://s3-us-west-1.amazonaws.com/udacity-content/course/images/ud953-d95e68e.jpg', description='A Brief Refresher (with Python!)', provider='Udacity', category_id=2, user_id=1) db.session.add(course) course = Course(name='Intro to Physics', level='Beginner', url='https://www.udacity.com/course/intro-to-physics--ph100', image_url='https://lh6.ggpht.com/9xDuLEr_4CuXcBZVbMQPagaUOvdUOH_T8V4I9Nm9XvDogvR4_yudI60v5_0tWedKx2LInYQiV6KOGqNPXuo=s0#w=436&h=268', description='Landmarks in Physics', provider='Udacity', category_id=3, user_id=1) db.session.add(course) course = Course(name='Deep Learning', level='Advanced', url='https://www.udacity.com/course/deep-learning--ud730', image_url='https://s3-us-west-1.amazonaws.com/udacity-content/course/images/ud730-b3af4bf.jpg', description='Take machine learning to the next level', provider='Udacity', category_id=4, user_id=1) db.session.add(course) db.session.commit() for course in db.session.query(Course).all(): print course.id, course.name, 'in', course.category.name
def setup_profile(): cats, pager = Category.paginate(page_size=40) return {'categories': cats, 'pager': pager}
def get_root_category(): qs = Category.get_root() return qs
('Q', 'IV Supplies'), ('R', 'Anesthesia'), ('S', 'Sutures'), ('T', 'Cautery'), ('U', 'Surgical Linens'), ('V', 'Surgical Miscellanea'), ('W', 'Surgical Supplies'), ('X', 'Plastic'), ('Y', 'UNKNOWN'), ('Z', 'Little Things'), ('#', 'Equipment')) categories = Category.objects.all() categories.delete() for pair in letter_mapping: category = Category(letter=pair[0], name=pair[1]) category.save() box_name = BoxName.objects.all() box_name.delete() box_name_mapping = ( #(box name, category letter, does it expire, do we count it) ('Adult Diapers','B',False,False), ('OB Pads','A', True,False), ('OB/GYN Mix','A', True,False), ('Pediatric Diapers','A', True,False), ('Pediatric Supplies','A', True,False), ('Speculums','A',False,True), ('Anti-Embolism Stockings','B', True,True), ('Oral Care','B', True,False),
def handle(self, *args, **options): start_time = time.time() # going to disconnect categories counter update hook from Product Signal.disconnect(pre_save, sender=Product, receiver=counters_hook) # going to disconnect product medial hook Signal.disconnect(post_delete, sender=ProductMedia, receiver=product_image_delete) if options['delete']: Category.objects.all().delete(); Product.objects.all().delete(); for file in args: if file[0:4] == 'http': try: request = urllib2.Request(file, headers={"Accept": "application/xml"}) file = urllib2.urlopen(request) tree = ET.parse(file) except ET.ParseError: raise CommandError('YML "%s" is not valid' % file) else: tree = ET.parse(file) root = tree.getroot() trans_dct = {} # copy categories into databases for child in root.find('shop').find('categories'): category = Category(name=child.text); category.save() trans_dct[child.get('id')] = category.id; # setting child-parent relations for child in root.find('shop').find('categories'): # only for child elements if child.get('parentId') is not None: # search for child a category try: category = Category.objects.get(pk=trans_dct[child.get('id')]) except Category.DoesNotExist: raise CommandError('Category ID "%s" was not found' % child.get('id')) pass # adding relation to parent category try: category.parent = Category.objects.get(pk=trans_dct[child.get('parentId')]) category.save() except Category.DoesNotExist: raise CommandError('Category ID "%s" was not found' % child.get('id')) pass self.stdout.write('Categories imported' + '\n') # import offers (products) product_counter = 0 for child in root.find('shop').find('offers'): if options['verbose']: u = u'import products) %s ' % child.find('name').text print u.encode('ascii', 'ignore') description = child.find('description').text; if description is None: description = "" product = Product( name=child.find('name').text, price=child.find('price').text, description=description, category=Category.objects.get(pk=trans_dct[child.find('categoryId').text]) ); product.save() product_counter += 1 if options['images']: # importing images from <picture>http://...</picture> if child.find('picture') is not None: try: image_data = urllib2.urlopen(child.find('picture').text, timeout=5) except urllib2.HTTPError: print 'Could not download image: ' + child.find('picture').text else: filename = urlparse.urlparse(image_data.geturl()).path.split('/')[-1] + '.jpg' product_media = ProductMedia(image=filename, is_main=True, product=product) product_media.image.save(filename, ContentFile(image_data.read()), save=False) product_media.save() self.stdout.write('Products imported - ' + str(product_counter) + '\n' + str(round(time.time() - start_time, 2)) + " seconds") # fix categories counters categories = Category.objects.all() for category in categories: category.count_products = Product.active.filter( category__in=category.get_descendants(include_self=True)).count() # deactivate empty categories if category.count_products == 0: category.is_active = False category.save()
def setUp(self): new_category = Category() new_category.name = "Moins de gras" new_category.save()
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['categories'] = Category.get_annotated_list(max_depth=2) return context
def test_category_import(self): csv = Category.create_from_csv(self.test_csv) self.assertTrue(Category.objects.get(letter="T") is not None)
def setUp(self): self.cat = Category(letter="C", name="Mother and Child") self.cat.save() self.data = BoxName.objects.create(category=self.cat, name="Data")