def registration(request): """Страничка для регистрации""" mh_vars = reg_vars.copy() context = {} q_string = {} containers = {} if request.is_ajax(): return JsonResponse(context, safe=False) template = 'web/login/registration.html' page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=mh_vars['singular_obj']) context['breadcrumbs'] = [{ 'name': 'Регистрация', 'link': reverse('%s:%s' % (CUR_APP, 'registration')), }] context['page'] = page context['containers'] = containers context['vk_link'] = VK().get_auth_user_link() context['yandex_link'] = Yandex().get_auth_user_link() return render(request, template, context)
def login(request): """Авторизация пользователя""" context = {} q_string = {} containers = {} result = login_from_site(request) if isinstance(result, list): context['errors'] = result else: save_user_to_request(request, result) context['shopper'] = result.to_dict() context['redirect'] = reverse('%s:%s' % (CUR_APP, 'show_profile')) if request.is_ajax(): return JsonResponse(context, safe=False) template = 'web/login/registration.html' page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=reg_vars['singular_obj']) context['breadcrumbs'] = [{ 'name': 'Регистрация', 'link': reverse('%s:%s' % (CUR_APP, 'registration')), }] context['page'] = page context['containers'] = containers context['vk_link'] = VK().get_auth_user_link() context['yandex_link'] = Yandex().get_auth_user_link() return render(request, template, context)
def checkout(request): """Оформление заказа - Подтверждение заказа""" mh_vars = order_vars.copy() context = {} q_string = {} containers = {} shopper = get_shopper(request) if request.is_ajax(): return JsonResponse(context, safe=False) template = 'web/order/checkout.html' page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=order_vars['singular_obj']) context['breadcrumbs'] = [{ 'name': 'Подтверждение заказа', 'link': reverse('%s:%s' % (CUR_APP, 'checkout')), }] context['page'] = page context['containers'] = containers cart = calc_cart(shopper, min_info=False) context['cart'] = cart # Оформление заказа context.update(**create_new_order(request, shopper, cart)) if 'order' in context and context['order']: template = 'web/order/confirmed.html' return render(request, template, context)
def show_cart(request): """Оформление заказа - Корзинка""" mh_vars = cart_vars.copy() context = {} q_string = {} containers = {} shopper = get_shopper(request) if request.is_ajax(): return JsonResponse(context, safe=False) template = 'web/order/cart.html' page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=mh_vars['singular_obj']) context['breadcrumbs'] = [{ 'name': 'Корзина', 'link': reverse('%s:%s' % (CUR_APP, 'show_cart')), }] context['page'] = page context['containers'] = containers context['cart'] = calc_cart(shopper, min_info=False) return render(request, template, context)
def show_order(request, order_id: int): """Просмотр оформленного заказа""" mh_vars = order_vars.copy() context = {} q_string = {} containers = {} shopper = get_shopper(request) if request.is_ajax(): return JsonResponse(context, safe=False) template = 'web/order/order.html' page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=mh_vars['singular_obj']) context['breadcrumbs'] = [{ 'name': 'Заказ', 'link': reverse('%s:%s' % (CUR_APP, 'show_order'), kwargs={'order_id': order_id}), }] context['page'] = page context['containers'] = containers result = get_order(shopper, order_id) context['cart'] = result.get('cart', {}) context['cart']['purchases'] = result.get('purchases', []) context['order'] = result.get('order') return render(request, template, context)
def get_product_for_site(request, price_id: int): """Получить товар/услугу для сайта""" page = None photos = None rubric = None breadcrumbs = [] product = Products.objects.filter(pk=price_id).first() if product: page = Blocks(name=product.name) photos = product.productsphotos_set.all() # --------------------------- # достаем рубрики товара # рассчитываем хлебные крошки # --------------------------- rubric = get_breadcrumbs_for_product(product, breadcrumbs) get_props_for_products([product]) get_costs_types([product]) result = { 'breadcrumbs': breadcrumbs, 'cat': rubric, 'photos': photos, 'page': page, 'product': product, } return result
def show_sitemap(self, request): """Формирование ссылок для карты сайта :param request: HttpRequest TODO: постраничная навигация TODO: выполнять кроном и ложить в кэш/файл """ managers = self.get_menu_managers() context = {} q_string = {} containers = {} # для перевода all_containers = [] all_blocks = [] for key, manager in managers.items(): query = Blocks.objects.filter( container__in=manager['containers']).order_by('position') manager['structure'] = [] for container in manager['containers']: menus = [] blocks = [ block for block in query if block.container_id == container ] recursive_fill(blocks, menus, parents='') sort_voca(menus) container = Containers.objects.filter(pk=container).first() all_containers.append(container) all_blocks += blocks manager['structure'].append({ 'container': container, 'blocks': menus }) # Переводим блоки/контейнеры if settings.IS_DOMAINS and request: domains = get_domains() domain = get_domain(request, domains) if domain: domains = [domain] get_translate(all_blocks, domains) translate_rows(all_blocks, domain) get_translate(all_containers, domains) translate_rows(all_containers, domain) context['managers'] = managers page = SearchLink(q_string, request, containers) if not page: page = Blocks(name='Карта сайта') context['breadcrumbs'] = [{ 'name': page.name, 'link': '/sitemap/', }] context['page'] = page context['containers'] = containers template = 'sitemap_html.html' return render(request, template, context)
def checkout(request): """Оформление заказа - Подтверждение заказа""" mh_vars = order_vars.copy() context = {} q_string = {} containers = {} shopper = get_shopper(request) if request.is_ajax(): return JsonResponse(context, safe=False) template = 'web/order/checkout.html' page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=order_vars['singular_obj']) context['breadcrumbs'] = [{ 'name': 'Подтверждение заказа', 'link': reverse('%s:%s' % (CUR_APP, 'checkout')), }] context['page'] = page context['containers'] = containers cart = calc_cart(shopper, min_info=False) context['cart'] = cart # Оформление заказа comments = None wrist_size = request.POST.get('wrist_size') birthday = request.POST.get('birthday') if wrist_size or birthday: comments = [] if wrist_size: comments.append('Размер запястья %s' % wrist_size) if birthday: comments.append('День рождения %s' % birthday) comments = ', '.join(comments) context.update(**create_new_order(request, shopper, cart, comments)) if 'order' in context and context['order']: template = 'web/order/confirmed.html' payment = YandexKassa().create_payment( domain='%s%s' % ('https://' if request.is_secure() else 'http://', request.META['HTTP_HOST']), summa='%s' % context['order'].total, desc='Оплата заказа №%s' % context['order'].id, ) if 'confirmation' in payment: context['yandex_payment_link'] = payment['confirmation'][ 'confirmation_url'] Transactions.objects.create(order=context['order'], uuid=payment['id'], ptype=1) return render(request, template, context)
def recursive_fill_blocks(container, blocks: list, parent_block, parents: str, blocks_path: str): """Рекурсивное создание блоков контейнера :param container: контейнер блоков :param blocks: блоки, которые надо создать в контейнере :param parent_block: родительский блок :param parents: родительский блок :param blocks_path: путь к изображениям блоков """ for json_obj in blocks: if not parents == json_obj['parents']: continue block = Blocks(container=container) for k, v in json_obj.items(): if k in ('img', 'id', 'parents', 'container'): continue setattr(block, k, v) if parent_block: block.parents = '%s_%s' % (parent_block.parents or '', parent_block.id) block.save() imga = json_obj.get('img') if imga: copy_file(os.path.join(blocks_path, imga), os.path.join(block.get_folder(), imga)) Blocks.objects.filter(pk=block.id).update(img=imga) # Теперь надо найти подблоки этого блока recursive_fill_blocks( container, blocks, block, '%s_%s' % (json_obj['parents'] or '', json_obj['id']), blocks_path)
def payment(request, provider: str, action: str): """Оплата заказа :param request: HttpRequest :param provider: sbrf/ :param action: success/fail """ mh_vars = payment_vars.copy() context = { 'provider': provider, 'action': action, } q_string = {} containers = {} shopper = get_shopper(request) if request.is_ajax(): return JsonResponse(context, safe=False) template = 'web/order/payment.html' page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=order_vars['singular_obj']) kwargs = { 'provider': provider, 'action':action, } context['breadcrumbs'] = [{ 'name': 'Оплата заказа', 'link': reverse('%s:%s' % (CUR_APP, 'payment'), kwargs=kwargs), }] context['page'] = page context['containers'] = containers if request.GET.get('orderId'): order_id = request.GET['orderId'] order = Orders.objects.filter(shopper=shopper, external_number=order_id).first() if order: sber = SberPaymentProovider() order_status = sber.get_order_status(order.external_number, order.id) context['order_status'] = order_status context['order'] = order return render(request, template, context)
def checkout(request): """Оформление заказа - Подтверждение заказа""" mh_vars = order_vars.copy() context = {} q_string = {} containers = {} shopper = get_shopper(request) if request.is_ajax(): return JsonResponse(context, safe=False) template = 'web/order/checkout.html' page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=order_vars['singular_obj']) context['breadcrumbs'] = [{ 'name': 'Подтверждение заказа', 'link': reverse('%s:%s' % (CUR_APP, 'checkout')), }] context['page'] = page context['containers'] = containers cart = calc_cart(shopper, min_info=False) context['cart'] = cart # Оформление заказа context.update(**create_new_order(request, shopper, cart)) if 'order' in context and context['order']: template = 'web/order/confirmed.html' # Если пользователь вернулся # на страничку оформленного заказа, # например, для оплаты if request.GET.get('order_id'): order_id = request.GET['order_id'] if order_id.isdigit(): order = Orders.objects.filter(pk=order_id, shopper=shopper).first() if order: template = 'web/order/confirmed.html' context['order'] = order return render(request, template, context)
def registration(request): """Страничка для регистрации""" mh_vars = reg_vars.copy() context = {} q_string = {} containers = {} shopper = get_shopper(request) if shopper: return redirect(reverse('%s:%s' % (CUR_APP, 'show_profile'))) # ----------- # регистрация # ----------- if request.method == 'POST': result = register_from_site(request) if isinstance(result, list): context['errors'] = result else: save_user_to_request(request, result) context['shopper'] = result.to_dict() context['redirect'] = reverse('%s:%s' % (CUR_APP, 'show_profile')) if request.is_ajax(): return JsonResponse(context, safe=False) template = 'web/login/registration.html' page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=reg_vars['singular_obj']) context['breadcrumbs'] = [{ 'name': mh_vars['singular_obj'], 'link': reverse('%s:%s' % (CUR_APP, 'registration')), }] context['page'] = page context['containers'] = containers context['vk_link'] = VK().get_auth_user_link() context['yandex_link'] = Yandex().get_auth_user_link() return render(request, template, context)
def show_profile(request): """Личный кабинет пользователя""" mh_vars = profile_vars.copy() context = { 'fs_server': settings.FREESWITCH_DOMAIN, 'tab': request.GET.get('tab'), } q_string = {} containers = {} shopper = get_shopper(request) if not shopper: return redirect(reverse('%s:%s' % (CUR_APP, 'login'))) if request.method == 'POST': result = update_profile_from_site(request) if isinstance(result, list): context['errors'] = result else: save_user_to_request(request, result) context['shopper'] = result.to_dict() context['redirect'] = reverse('%s:%s' % (CUR_APP, 'show_profile')) if request.is_ajax(): return JsonResponse(context, safe=False) template = 'web/login/profile.html' page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=mh_vars['singular_obj']) context['breadcrumbs'] = [{ 'name': 'Ваш аккаунт', 'link': reverse('%s:%s' % (CUR_APP, 'show_profile')), }] context['page'] = page context['containers'] = containers context['shopper'] = shopper #context['orders'] = Orders.objects.filter(shopper=shopper).order_by('-created')[:50] return render(request, template, context)
def transaction_success(request): """Оформление заказа - Успешная оплата""" mh_vars = order_vars.copy() context = {} q_string = {} containers = {} shopper = get_shopper(request) page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=order_vars['singular_obj']) context['breadcrumbs'] = [{ 'name': 'Заказ оплачен', 'link': reverse('%s:%s' % (CUR_APP, 'transaction_success')), }] context['page'] = page context['containers'] = containers template = 'web/order/transaction_success.html' return render(request, template, context)
def fill_seo(self, **kwargs): """Заполнение сео-полей/статей для товара, заполнение привязок к статьям (привязваем контейнеры) просто создаем ссылку с сео-полями по ссылке товара, """ if not self.id: return seo_fields = ('seo_title', 'seo_description', 'seo_keywords') linkcontainer = kwargs.get('linkcontainer', []) seo_block = None seo_tag = 'seo_for_products' product_tag = 'product_%s' % self.id link = self.link() seo_container = Containers.objects.filter(state=4, tag=seo_tag).first() if not seo_container: seo_container = Containers.objects.create( state=4, tag=seo_tag, name='Сео-тексты для товаров/услуг') seo_blocks = seo_container.blocks_set.filter( models.Q(tag=product_tag) | models.Q(link=link)) # Если по id не найден блок, # тогда пробуем найти по ссылке if not seo_blocks: seo_block = Blocks( state=4, container=seo_container, tag=product_tag, link=link, ) else: for block in seo_blocks: if block.tag == product_tag: seo_block = block break if not seo_block: seo_block = seo_blocks[0] seo_block.link = link seo_block.name = self.name for key in seo_fields: field = key.replace('seo_', '') setattr(seo_block, field, kwargs.get(key)) seo_block.save() link_containers2block(seo_block, linkcontainer)
def fill_catalogue(branches: list, container: Containers, parent: Blocks = None): """Заполнить каталог иерархией :param branches: рубрики :param container: контейнер каталога :param parents: родительский блок """ for branch in branches: if branch['name'].startswith('__'): continue tag = 'cat_%s' % branch['id'] analog = container.blocks_set.filter(tag=tag).first() if not analog: analog = Blocks(tag=tag, container=container) analog.name = branch['name'] if parent: root_parents = parent.parents if parent.parents else '' analog.parents = '%s_%s' % (root_parents, parent.id) analog.state = 4 analog.save() sub_branches = branch.get('branches') if sub_branches: fill_catalogue(sub_branches, container, analog)
def handle(self, *args, **options): """Импорт со старой админки """ pass_img = options.get('pass_img') host = 'http://pizzahot.me' endpoint = '/media/unloading.json' r = requests.get('%s%s' % (host, endpoint)) content = json.loads(r.text) costs_types = content.get('costs_types', {}) for pk, cost_type in costs_types.items(): analog = CostsTypes.objects.filter(pk=pk).first() if not analog: analog = CostsTypes(pk=pk) for field in ('name', 'tag', 'currency'): setattr(analog, field, prepare_value(cost_type[field])) analog.save() costs_types[pk]['analog'] = analog products = content.get('products') for pk, product in products.items(): analog = Products.objects.filter(pk=pk).first() if not analog: analog = Products(pk=pk) product['code'] = product['kod'] for field in ('name', 'altname', 'manufacturer', 'measure', 'price', 'dj_info', 'mini_info', 'info', 'code', 'count', 'position'): setattr(analog, field, prepare_value(product[field])) analog.save() if product['img'] and not pass_img: analog.upload_img('%s%s' % (host, product['img'])) products[pk]['analog'] = analog costs = content.get('costs') for pk, cost in costs.items(): analog = Costs.objects.filter(pk=pk).first() if not analog: analog = Costs(pk=pk) for field in ('measure', 'cost'): setattr(analog, field, prepare_value(cost[field])) analog.product = products[str(cost['product'])]['analog'] analog.cost_type = costs_types[str(cost['cost_type'])]['analog'] analog.save() costs[pk]['analog'] = analog photos = content.get('photos') for pk, photo in photos.items(): analog = ProductsPhotos.objects.filter(pk=pk).first() if not analog: analog = ProductsPhotos(pk=pk) photo['name'] = photo['description'] for field in ('name', ): setattr(analog, field, prepare_value(photo[field])) analog.product = products[str(photo['product'])]['analog'] analog.save() if photo['img'] and not pass_img: analog.upload_img('%s%s' % (host, photo['img'])) photos[pk]['analog'] = analog rubrics = content.get('rubrics') catalogue = Containers.objects.filter(tag='catalogue').first() for pk, rubric in rubrics.items(): if not rubric['parents']: continue analog = Blocks.objects.filter(container=catalogue, tag='cat_%s' % pk).first() if not analog: analog = Blocks(container=catalogue, state=4, tag='cat_%s' % pk) rubric['title'] = rubric['altname'] for field in ('name', 'title', 'keywords', 'position'): setattr(analog, field, prepare_value(rubric[field])) analog.parents = None analog.container = catalogue analog.state = 4 analog.link = None analog.save() if rubric['img'] and not pass_img: analog.upload_img('%s%s' % (host, rubric['img'])) rubrics[pk]['analog'] = analog rubrics[pk]['tags_parents'] = [ 'cat_%s' % item for item in rubric['parents'].split('_') if item ] print(rubrics[pk]['tags_parents']) # TODO: Пофиксить parents # Первый tags_parents надо пропустить, # т/к мы верхний уровень игнорим, # потому что в старой админке это была рубрика Каталог, # далее надо по каждому tags_parents достать рубрику # и обновить parents cats = content.get('cats') for pk, cat in cats.items(): analog = ProductsCats.objects.filter(pk=pk).first() if not analog: analog = ProductsCats(pk=pk) analog.product = products[str(cat['product'])]['analog'] analog.container = catalogue analog.cat = rubrics[str(cat['cat'])]['analog'] analog.save() cats[pk]['analog'] = analog properties = content.get('properties') for pk, prop in properties.items(): analog = Property.objects.filter(pk=pk).first() if not analog: analog = Property(pk=pk) prop['code'] = prop['tag'] for field in ('name', 'code', 'ptype'): setattr(analog, field, prepare_value(prop[field])) analog.save() properties[pk]['analog'] = analog pvalues = content.get('pvalues') for pk, pvalue in pvalues.items(): analog = PropertiesValues.objects.filter(pk=pk).first() if not analog: analog = PropertiesValues(pk=pk) pvalue['str_value'] = pvalue['t_value'] pvalue['digit_value'] = pvalue['i_value'] for field in ('str_value', 'digit_value'): setattr(analog, field, prepare_value(pvalue[field])) analog.prop = properties[str(pvalue['prop'])]['analog'] analog.save() pvalues[pk]['analog'] = analog products_props = content.get('products_props') for pk, product_prop in products_props.items(): analog = ProductsProperties.objects.filter(pk=pk).first() if not analog: analog = ProductsProperties(pk=pk) analog.product = products[str(product_prop['product'])]['analog'] analog.prop = pvalues[str(product_prop['pvalue'])]['analog'] analog.save() products_props[pk] = analog
def checkout(request): """Оформление заказа - Подтверждение заказа""" mh_vars = order_vars.copy() context = {} q_string = {} containers = {} shopper = get_shopper(request) if request.is_ajax(): return JsonResponse(context, safe=False) template = 'web/order/checkout.html' page = SearchLink(q_string, request, containers) if not page: page = Blocks(name=order_vars['singular_obj']) context['breadcrumbs'] = [{ 'name': 'Подтверждение заказа', 'link': reverse('%s:%s' % (CUR_APP, 'checkout')), }] context['page'] = page context['containers'] = containers cart = calc_cart(shopper, min_info=False) context['cart'] = cart # Оформление заказа context.update(**create_new_order(request, shopper, cart)) if 'order' in context and context['order']: template = 'web/order/confirmed.html' # Если пользователь вернулся # на страничку оформленного заказа, # например, для оплаты if request.GET.get('order_id'): order_id = request.GET['order_id'] if order_id.isdigit(): order = Orders.objects.filter(pk=order_id, shopper=shopper).first() if order: template = 'web/order/confirmed.html' context['order'] = order sber = SberPaymentProovider() order_status = sber.get_order_status(order.external_number, order.id) context['order_status'] = order_status # ----------------------------------------- # Если пользователь пытается оплатить заказ # ----------------------------------------- if 'order' in context and request.GET.get('pay') == 'sbrf': order = context['order'] scheme = 'http://' if request.is_secure(): scheme = 'https://' host = '%s%s' % (scheme, request.META['HTTP_HOST']) env = '' if settings.DEBUG: env = 'test_%s' % str(time.time()) params = { 'amount': int(order.total * 100), 'orderNumber': '%s%s' % (env, order.id), 'returnUrl': '%s/payment/sbrf/success/' % host, 'failUrl': '%s/payment/sbrf/fail/' % host, #'description': 'Тестовый заказ', 'clientId': shopper.id, 'email': shopper.email, 'phone': shopper.phone, } sber = SberPaymentProovider() register_order = sber.register_do(**params) context.update(register_order) # ------------------------ # Переадресация на форму и # запись номера заказа # ------------------------ if 'formUrl' in register_order: Orders.objects.filter(pk=order.id).update(external_number=register_order['orderId']) return redirect(register_order['formUrl']) return render(request, template, context)
def get_cat_for_site(request, link: str = None, with_props: bool = True, with_filters: bool = True, **kwargs): """Для ображения каталога на сайте по link :param link: ссылка на рубрику (без /cat/ префикса) :param with_props: Вытащить свойства товаров :param with_filters: Вытащить свойства для фильтров, например, максимальная и минимальная цена """ cat_type = get_ftype('flatcat', False) page = Blocks(name='Каталог') containers = {} catalogue = None breadcrumbs = [] q_string = kwargs.get('q_string', {}) is_search = False search_terms = [] if not link: link = '/cat/' else: link = '/cat/%s' % link if not link.endswith('/'): link = '%s/' % link q_string_fill(request, q_string) # Поиск альтернативных каталогов tag = settings.DEFAULT_CATALOGUE_TAG catalogue_tag, is_root_level = search_alt_catalogue(link) if catalogue_tag: tag = catalogue_tag if link == '/cat/' or is_root_level: is_root_level = True # Поиск всегда идет на /cat/ q = q_string['q'].get('q') catalogue = Containers.objects.filter(tag=tag, state=cat_type).first() if not catalogue: catalogue = create_new_cat() page.name = catalogue.name page.link = link if q: page.name = 'Вы искали %s' % q ids_products, search_terms = search_products(q) is_search = True query = Products.objects.filter(pk__in=ids_products) else: query = ProductsCats.objects.filter(product__isnull=False, container=catalogue) else: page = Blocks.objects.select_related('container').filter( link=link, container__state=cat_type).first() if page: catalogue = page.container query = ProductsCats.objects.filter(cat__container=catalogue, product__is_active=True) if not catalogue: return { 'page': page, 'q_string': q_string, 'breadcrumbs': breadcrumbs, 'error': 404, } if not is_root_level: breadcrumbs.append({ 'name': catalogue.name, 'link': catalogue.cat_link() }) page_parents = page.parents if page.parents else '' cond = Q() cond.add(Q(cat=page), Q.OR) cond.add(Q(cat__parents='%s_%s' % (page_parents, page.id)), Q.OR) cond.add( Q(cat__parents__startswith='%s_%s_' % (page_parents, page.id)), Q.OR) # Выбираем только активные pk_arr = ProductsCats.objects.filter( cond, cat__is_active=True).values_list('id', flat=True) pk_arr = list(pk_arr) # чтобы в subquery не уходило query = query.filter(pk__in=pk_arr, product__is_active=True) if page.parents: ids_parents = [ int(parent) for parent in page.parents.split('_') if parent ] parents = {} search_parents = Blocks.objects.filter(pk__in=ids_parents) for parent in search_parents: parents[parent.id] = parent for item in ids_parents: parent = parents[item] breadcrumbs.append({'name': parent.name, 'link': parent.link}) prefix = 'product__' if is_search: prefix = '' # ----------------------------- # Фильтрация ProductsProperties # В рамках одного свойства # надо фильтровать по ИЛИ, не И # ----------------------------- facet_filters = get_facet_filters(request) if facet_filters: query = query.filter( **{'%sid__in' % (prefix, ): facet_filters['ids_products']}) breadcrumbs.append({'name': page.name, 'link': page.link}) total_records = query.aggregate(Count('id'))['id__count'] # Сортировка sort = request.GET.get('sort') if sort == 'price': query = query.order_by('%smin_price' % prefix) q_string['q']['sort'] = 'price' q_string['sort_name_filter'] = 'Цена по возрастанию' elif sort == '-price': query = query.order_by('-%smax_price' % prefix) q_string['q']['sort'] = '-price' q_string['sort_name_filter'] = 'Цена по убыванию' else: # По умолчанию сортировка по позиции query = query.order_by('%sposition' % prefix) paginator_template = 'web/paginator.html' my_paginator, records = myPaginator(total_records, q_string['page'], q_string['by']) paginator = navigator(my_paginator, q_string, paginator_template) # Фильтры по свойствам # Фильтр по цене, но только если не сильно много товаров # в противном случае это аяксом надо делать cost_filter = None if with_filters and total_records < FAT_HIER: costs = query.aggregate(Max('%sprice' % prefix), Min('%sprice' % prefix)) cost_filter = { 'min': costs['%sprice__min' % prefix], 'max': costs['%sprice__max' % prefix], } if is_search: products = query[records['start']:records['end']] breadcrumbs.append({ 'name': 'Вы искали %s' % q, 'link': '%s?q=%s' % (page.link, q) }) else: query = query.select_related('product') cat_products = query[records['start']:records['end']] products = [product.product for product in cat_products] if with_props: get_props_for_products(products) get_costs_types(products) # TODO: кэшировать по ссылке return { 'page': page, 'q_string': q_string, 'breadcrumbs': breadcrumbs, 'catalogue': catalogue, 'paginator': paginator, 'my_paginator': my_paginator, 'products': products, 'cost_filter': cost_filter, 'search_terms': search_terms, 'facet_filters': facet_filters.get('facet_filters'), }
def dynamic_portfolio(request): cache_time = 300 cache_var = '%s_dynamic_portfolio' % (settings.PROJECT_NAME, ) domains = get_domains() domain = get_domain(request, domains) if domain: cache_var += '_%s' % domain['pk'] inCache = cache.get(cache_var) if inCache and not request.GET.get('force_new'): return inCache # Вытаскиваем менюшку portfolio portfolio_menu = Blocks.objects.filter(tag='portfolio', link='/portfolio/', state=4).first() if not portfolio_menu: return {} parents = '%s_%s' % (portfolio_menu.parents, portfolio_menu.id) all_blocks = Blocks.objects.filter(state=4, is_active=True).filter( Q(parents=parents) | Q(parents__startswith='%s_' % parents)) all_blocks = [ block for block in all_blocks if not block.link == '/portfolio/' ] if domain: domains = [domain] get_translate(all_blocks, domains) translate_rows(all_blocks, domain) menu_queryset = [] recursive_fill(all_blocks, menu_queryset, parents) blocks = sort_voca(menu_queryset) # К каждому блоку надо достать описание по сссылке descriptions = [] # К каждому блоку надо достать кол-во фоток # привязанных к подблокам, и из каждого подблока # первую фотку надо еще и выводить for block in blocks: if not hasattr(block, 'sub'): continue block.count = 0 block.images = [] ids_subblocks = {subblock.id: subblock.link for subblock in block.sub} # Для описания надо узнать какая стат.страничка # ссылается на subblock.link и взять от нее описание #related_by_link = Blocks.objects.filter(container__state=3, link__in=ids_subblocks.values()) related_by_link = [] related_containers = block.linkcontainer_set.select_related( 'container').all() if related_containers: related_by_link = related_containers[ 0].container.blocks_set.filter(link__in=ids_subblocks.values()) ids_desc = {related.link: related for related in related_by_link} # К каждому subblock надо докинуть описалово, чтобы получить его в картинках desc_arr = {} subblock_sorting = [] for subblock in block.sub: subblock_sorting.append(subblock.id) if subblock.link in ids_desc: desc_block = ids_desc[subblock.link] descriptions.append(desc_block) desc_arr[subblock.id] = desc_block links = LinkContainer.objects.filter( block__in=ids_subblocks.keys()).values('container', 'block') ids_links = { link['container']: { 'block_id': link['block'], 'position': subblock_sorting.index(link['block']), } for link in links } imgas = Blocks.objects.filter(container__in=ids_links.keys(), img__isnull=False).order_by('position') block.count += len(links) analogs = [] for imga in imgas: if imga.container_id in analogs: continue if imga.container_id in ids_links: block_id = ids_links[imga.container_id]['block_id'] # Нашли block_id надо взять его описание для этой фотки if block_id in desc_arr: imga.custom_block = desc_arr[block_id] imga.custom_pos = ids_links[imga.container_id]['position'] analogs.append(imga.container_id) block.images.append(imga) # Правильная сортировка изображений так как они в админке block.images.sort(key=lambda x: x.custom_pos if hasattr(x, 'custom_pos') else 0, reverse=True) # Перевод описаний вытащенных по ссылкам if domain: domains = [domain] get_translate(descriptions, domains) translate_rows(descriptions, domain) main_block = Blocks(name='All', title=blocks[0].title, class_name=blocks[0].class_name) main_block.images = [] main_block.count = 0 max_size = max([len(block.images) for block in blocks]) for i in range(max_size): for block in blocks: if len(block.images) > i: main_block.images.append(block.images[-(i + 1)]) main_block.count += 1 blocks.insert(0, main_block) result = { 'blocks': blocks, } cache.set(cache_var, result, cache_time) return result
def get_phones_for_site(request, link: str = None, **kwargs): """Для ображения телефонов на сайте по link :param link: ссылка на рубрику (без /phones/ префикса) """ page = Blocks(name='Телефоны 8800') search_terms = [] q_string = kwargs.get('q_string', {}) q = request.GET.get('q', '').strip() q_string_fill(request, q_string) catalogue = Containers.objects.filter(tag='phones8800').first() if not catalogue: catalogue = Containers.objects.create(name='Категории 8800', tag='phones8800', state=1) breadcrumbs = [{ 'name': catalogue.name, 'link': '/phones/', }] query = Phones.objects.all() cond = Q() # Выбираем только активные cond.add(Q(is_active=True), Q.AND) if link: link = '/phones/%s' % link if not link.endswith('/'): link = '%s/' % link menu = Blocks.objects.filter(link=link).first() if menu: cond.add(Q(menu=menu), Q.AND) breadcrumbs.append({ 'name': menu.name, 'link': link, }) query = query.filter(cond) if q: q_name = 'Вы искали "%s"' % q cond_q = Q() q_arr = q.split(' ') for item in q_arr: digit = item.strip().replace('-', '').replace('(', '').replace(')', '') if digit.isdigit(): cond_q.add(Q(phone__contains=digit), Q.AND) search_terms.append(digit) else: cond_q.add(Q(name__icontains=item.strip()), Q.AND) search_terms.append(item) query = query.filter(cond_q) breadcrumbs.append({ 'name': q_name, }) page.name = q_name total_records = query.aggregate(Count('id'))['id__count'] paginator_template = 'web/paginator.html' my_paginator, records = myPaginator(total_records, q_string['page'], q_string['by']) paginator = navigator(my_paginator, q_string, paginator_template) phones = query[records['start']:records['end']] # TODO: кэшировать по ссылке return { 'page': page, 'breadcrumbs': breadcrumbs, 'q_string': q_string, 'catalogue': catalogue, 'paginator': paginator, 'my_paginator': my_paginator, 'phones': phones, 'search_terms': search_terms, }