Exemplo n.º 1
0
def third_level_category(request, category_slug, second_category_slug, third_category_slug):
    try:
        _category = Category.objects.get(slug=third_category_slug)
    except:
        raise Http404

    display_categories = Category.objects.filter(is_active=True, parent_category=_category.parent_category).all()

    sorting = request.GET.get('sorting', 'price')
    abstract_products = Product.objects.filter(is_active=True, category=_category).order_by(sorting)
    paginator = Paginator(Product.objects.filter(is_active=True, category=_category).order_by(sorting), 20)
    products = paginator.page(request.GET.get('page', 1))

    available_brands = []
    for item in abstract_products:
        if item.brand not in available_brands:
            available_brands.append(item.brand)

    if request.is_ajax():
        return get_filtering_products(request, _category, sorting, contains=False)

    params = {
        'category': _category,
        'products': products,
        'level': 'third',
        'display_categories': display_categories,
        'total_product_count': Product.objects.filter(is_active=True, category=_category).count(),
        'sorting': sorting,
        'brands': available_brands,
        'min_price': abstract_products.filter(price__gte=0).order_by('price').first().price if abstract_products else 0,
        'max_price': abstract_products.filter(price__gte=0).order_by('price').last().price if abstract_products else 2000
    }
    params.update(generate_view_params(request))
    return render(request, 'app/category.html', params)
Exemplo n.º 2
0
def get_filtering_products(request, filtering_categories, sorting, contains=True):
    min_price = int(float(request.POST.get('min_price')))
    max_price = int(float(request.POST.get('max_price')))

    brand = json.loads(request.POST.get('brands', '[]'))

    filters = dict(
        price__lte=max_price,
        price__gte=min_price,
        is_active=True
    )
    if len(brand) > 1:
        filters['brand_id__in'] = brand
    elif len(brand) == 1:
        filters['brand_id'] = brand[0]

    if contains:
        filters['category__in'] = filtering_categories
    else:
        filters['category'] = filtering_categories

    paginator = Paginator(Product.objects.filter(**filters).order_by(sorting), 20)
    products = paginator.page(request.GET.get('page', 1))

    # print paginator.object_list

    params = {
        'products': products
    }
    params.update(generate_view_params(request))
    return render(request, 'app/partial/products.html', params)
Exemplo n.º 3
0
def list_of_comparison(request):
    if settings.COMPARISON_COOKIE_NAME in request.COOKIES:
        cookie_data = json.loads(
            request.COOKIES[settings.COMPARISON_COOKIE_NAME])
    else:
        cookie_data = []

    prepared_products = list()
    comparable_properties = list()
    for item in cookie_data:
        try:
            product = Product.objects.get(id=int(item))
        except:
            cookie_data = splice(cookie_data, item)
            continue

        prepared_products.append(product)
        for property in product.property.all():
            if not contains(comparable_properties, property.key.id,
                            field='id'):
                comparable_properties.append(property)

    params = {
        'products': prepared_products,
        'properties': comparable_properties
    }
    params.update(generate_view_params(request))
    return render(request, 'app/comparison.html', params)
Exemplo n.º 4
0
def news_list(request):
    news = Post.objects.filter(is_active=True).order_by('-created_at')

    params = {
        'news': news,
    }
    params.update(generate_view_params(request))
    return render(request, 'app/news.html', params)
Exemplo n.º 5
0
def news_single(request, slug):
    try:
        post = Post.objects.get(slug=slug)
    except ObjectDoesNotExist:
        raise Http404

    params = {'post': post}
    params.update(generate_view_params(request))
    return render(request, 'app/news-single.html', params)
Exemplo n.º 6
0
def promotions_single(request, slug):
    try:
        promotion = Promotion.objects.get(slug=slug)
    except:
        raise Http404

    params = {'promotion': promotion}
    params.update(generate_view_params(request))
    return render(request, 'app/promotion-single.html', params)
Exemplo n.º 7
0
def sign_up(request):
    _form = RegisterForm()
    messages = None

    if request.POST:
        _form = RegisterForm(request.POST)
        messages = list()
        if _form.is_valid():
            print _form.cleaned_data

            try:
                user = User.objects.get(email=_form.cleaned_data['email'])
                messages.append('This email already used!')
            except ObjectDoesNotExist:
                user = User(email=_form.cleaned_data['email'],
                            password=make_password(
                                _form.cleaned_data['password2']),
                            is_active=False)
                user.save()
                token = default_token_generator.make_token(user)
                uid = urlsafe_base64_encode(force_bytes(user.pk))
                template = loader.get_template(
                    'account/partial/confirm_email.html')
                protocol = 'https://' if request.is_secure() else 'http://'
                contexts = {
                    'link':
                    protocol + request.get_host() +
                    reverse('users:users_confirm',
                            kwargs={
                                'uidb64': uid,
                                'token': token
                            })
                }
                response = template.render(contexts, request)
                print contexts
                thread = threading.Thread(
                    target=send_email_notification,
                    args=(
                        'Activating profile | MyBrands.kg',
                        response,
                        [user.email],
                    ))

                thread.start()
                messages.append(
                    'We sent message with activation link on your email!')

        else:
            messages.append(
                'Somethings goes wrong... Please check the form for correctness of the filled data'
            )
            messages.append(_form.error_messages)

    params = {'form': _form, 'messages': messages}
    params.update(generate_view_params(request))
    return render(request, 'account/register.html', params)
Exemplo n.º 8
0
def product_single(request, product_slug):
    try:
        product = Product.objects.get(slug=product_slug)
    except:
        raise Http404

    suggested_products = Product.objects.filter(
        is_active=True, category=product.category).exclude(id=product.id)

    params = {
        'product': product,
        'suggested_products': suggested_products,
        'form': OrderInOneClickForm()
    }
    params.update(generate_view_params(request))
    return render(request, 'app/product-single.html', params)
Exemplo n.º 9
0
def parent_category(request, category_slug):
    try:
        _category = Category.objects.get(slug=category_slug)
    except:
        raise Http404

    filtering_categories = [_category]
    prepared_category = model_to_dict(_category)
    prepared_category['sub_categories'] = list()
    prepared_category['seo_thumbnail'] = _category.seo_thumbnail
    for sub_cat in Category.objects.filter(parent_category=_category, is_active=True).order_by('id'):
        filtering_categories.append(sub_cat)
        prepared_sub_category = model_to_dict(sub_cat)
        prepared_sub_category['seo_thumbnail'] = sub_cat.seo_thumbnail
        prepared_sub_category['sub_categories'] = list()
        prepared_sub_category['parent_category'] = Category.objects.get(id=prepared_sub_category['parent_category'])
        for _sub_cat in Category.objects.filter(parent_category=sub_cat, is_active=True).order_by('id'):
            filtering_categories.append(_sub_cat)
            prepared_sub_category['sub_categories'].append(_sub_cat)
        prepared_category['sub_categories'].append(prepared_sub_category)

    sorting = request.GET.get('sorting', 'price')
    abstract_products = Product.objects.filter(is_active=True, category__in=filtering_categories).order_by(sorting)
    paginator = Paginator(abstract_products, 20)
    products = paginator.page(request.GET.get('page', 1))

    available_brands = []
    for item in abstract_products:
        if item.brand not in available_brands:
            available_brands.append(item.brand)

    if request.is_ajax():
        return get_filtering_products(request, filtering_categories, sorting)

    params = {
        'category': prepared_category,
        'products': products,
        'level': 'parent',
        'total_product_count': Product.objects.filter(is_active=True, category__in=filtering_categories).count(),
        'sorting': sorting,
        'brands': available_brands,
        'min_price': abstract_products.filter(price__gte=0).order_by('price').first().price if abstract_products else 0,
        'max_price': abstract_products.filter(price__gte=0).order_by('price').last().price if abstract_products else 2000
    }
    #print params
    params.update(generate_view_params(request))
    return render(request, 'app/category.html', params)
Exemplo n.º 10
0
def calculator(request):
    try:
        _cat = Category.objects.get(slug='gipsokartonnye-sistemy')
    except:
        _cat = None

    second_categories = Category.objects.filter(parent_category=_cat)
    second_products = Product.objects.filter(
        category_id__in=[x.id for x in second_categories])
    calculation_form = CalculationForm()

    params = {
        'second_categories': second_categories,
        'second_products': second_products,
        'products': Product.objects.all(),
        'calculation_form': calculation_form,
    }
    params.update(generate_view_params(request))
    return render(request, 'app/calculator.html', params)
Exemplo n.º 11
0
def search(request):
    search_word = request.GET.get('search_word')

    result = None
    result_count = 0
    if search_word:
        query_list = search_word.split()
        holder = Product.objects.filter(
            reduce(operator.and_, (Q(title__icontains=q) for q in query_list)))
        result_count = holder.count()
        pagination = Paginator(holder, 20)
        result = pagination.page(request.GET.get('page', 1))

    params = {
        'search_word': search_word,
        'products': result,
        'result_count': result_count
    }
    params.update(generate_view_params(request))
    return render(request, 'app/search-results.html', params)
Exemplo n.º 12
0
def sign_in(request):
    _form = LoginForm()
    messages = None
    if request.POST:
        _form = LoginForm(request.POST)
        if _form.is_valid():
            messages = list()
            email = _form.cleaned_data['email']
            password = _form.cleaned_data['password']

            user = authenticate(email=email, password=password)
            if user:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect('/')
                else:
                    messages.append('User is not active')
            else:
                messages.append('Login or password is incorrect')

    params = {'form': _form, 'messages': messages}
    params.update(generate_view_params(request))
    return render(request, 'account/login.html', params)
Exemplo n.º 13
0
def confirm_email(request, uidb64, token):
    messages = list()
    if uidb64 is not None and token is not None:
        uid = urlsafe_base64_decode(uidb64)
        try:
            user = User.objects.get(pk=uid)
            if not user.is_active:
                if default_token_generator.check_token(user, token):
                    user.is_active = True
                    login(request, user)
                    messages.append(
                        'You have successfully activated your profile!')
                else:
                    messages.append('Link is incorrect')
            else:
                messages.append('Link is deprecated')
        except ObjectDoesNotExist:
            messages.append('User not found...')
    else:
        messages.append('Data is empty!')

    params = {'messages': messages}
    params.update(generate_view_params(request))
    return render(request, 'account/activate.html', params)
Exemplo n.º 14
0
def list_basket(request):
    if settings.BASKET_COOKIE_NAME in request.COOKIES:
        cookie_data = json.loads(request.COOKIES[settings.BASKET_COOKIE_NAME])
    else:
        cookie_data = []

    prepared_objects = []
    total_price = 0
    total_weight = 0
    for row in cookie_data:
        try:
            product = Product.objects.get(id=int(row['product_id']))
        except ObjectDoesNotExist:
            cookie_data = splice_row(cookie_data, row['id'])
            continue
        product_weight = product.property.filter(
            key_id=get_weight_property_object()).first()
        item = {
            'product': product,
            'count': row['count'],
            'row_price': product.get_price() * int(row['count']),
            'id': row['id']
        }
        total_price += item['row_price']
        if product_weight:
            total_weight += float(product_weight.value) * int(row['count'])
        prepared_objects.append(item)

    params = {
        'basket': prepared_objects,
        'total_price': total_price,
        'product_count': len(prepared_objects),
        'total_weight': total_weight
    }
    params.update(generate_view_params(request))
    return render(request, 'app/basket.html', params)
Exemplo n.º 15
0
def profile(request):
    params = {'user': request.user}
    params.update(generate_view_params(request))
    return render(request, 'account/profile.html', params)
Exemplo n.º 16
0
def promotions_list(request):
    params = {'promotions': Promotion.objects.filter(is_active=True)}
    params.update(generate_view_params(request))
    return render(request, 'app/promotions-list.html', params)
Exemplo n.º 17
0
def checkout(request):
    form = CheckoutForm(request.POST)
    params = {'form': form}
    if request.POST:
        if form.is_valid():
            if settings.BASKET_COOKIE_NAME in request.COOKIES:
                cookie_data = json.loads(
                    request.COOKIES[settings.BASKET_COOKIE_NAME])

                order_object = Order(name=form.cleaned_data['name'],
                                     email=form.cleaned_data['email'],
                                     phone=form.cleaned_data['phone'],
                                     address=form.cleaned_data['address'])
                order_object.save()

                total_weight = 0
                for item in cookie_data:
                    try:
                        product = Product.objects.get(
                            id=int(item['product_id']))
                    except ObjectDoesNotExist:
                        cookie_data = splice_row(cookie_data, item['id'])
                        continue
                    total_weight += (float(
                        product.property.filter(
                            key_id=get_weight_property_object()).first().value)
                                     * int(item['count']))
                    order_item = OrderRow.objects.create(product=product,
                                                         count=int(
                                                             item['count']))
                    order_object.order_items.add(order_item)

                order_object.total_weight = total_weight

                order_object.save()

                # отсюда и до save создание файла excel отчёта

                workbook = Workbook()
                sheet = workbook.active
                sheet.title = "Заказ"

                sheet.append([
                    'Артикул', 'Название', 'Категория', 'Количество', 'Цена',
                    'Стоимость'
                ])

                for item in order_object.order_items.all():
                    sheet.append([
                        item.product.article, item.product.title,
                        item.product.category.title, item.count,
                        item.product.get_price(),
                        item.count * item.product.get_price()
                    ])

                sheet.append([
                    '', '', '', '', 'Общая стоимость:',
                    order_object.get_order_full_price()
                ])

                excel_file = 'order/' + str(order_object.id) + '.xlsx'

                workbook.save(settings.MEDIA_ROOT + excel_file)

                order_object.excel_file = excel_file

                order_object.save()

                template = loader.get_template('app/email/order.html')
                protocol = 'https://' if request.is_secure() else 'http://'
                context = {
                    'link':
                    protocol + request.get_host() + reverse(
                        'admin:order_order_change', args=(order_object.id, ))
                }
                mail_body = template.render(context, request)

                thread = threading.Thread(
                    target=send_email_notification,
                    args=('Новый заказ | Vesta Stroy', mail_body,
                          [x.email for x in AdminEmails.objects.all()]))
                thread.start()

                params['success'] = True

            else:
                params['success'] = False
                params['error'] = 'Вы не добавили товаров в карзину'
        else:
            params['success'] = False
            params['error'] = str(form.errors)

    params.update(generate_view_params(request))
    return render(request, 'app/paypal.html', params)