Example #1
0
def about(request):

    for_cat_menu = Category.objects.all()

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'],
                                              cart__status=True)

    else:
        for_cart = CartElement.objects.filter(
            cart__owner__user__username=request.user.username,
            cart__status=True)
    l = len(for_cart)
    template = loader.get_template('bshop/about.html')
    context = {
        'menu': for_cat_menu,
        'path': request.path,
        'user': request.user,
        'session': request.session,
        'cart_length': l,
        'summ_in_cart': summ_in_cart(for_cart)
    }
    return HttpResponse(template.render(context, request))
Example #2
0
def admin_element(request, element="0"):
    permission_req_ = 'shop.change_order'
    if not request.user.has_perm(permission_req_):
        raise Http404()
    else:
        for_cat_menu = Category.objects.all()
        for_cart = CartElement.objects.filter(
            cart__owner__user__username=request.user.username,
            cart__status=True)
        l = len(for_cart)

        element_ = get_object_or_404(CartElement, id=element)
        if request.method == 'GET':
            template = loader.get_template('bshop/admin_element.html')
            context = {
                'menu': for_cat_menu,
                'request': request,
                'path': request.path,
                'user': request.user,
                'session': request.session,
                'cart_length': l,
                'summ_in_cart': summ_in_cart(for_cart),
                'element': element_
            }

            return HttpResponse(template.render(context, request))

        elif request.method == 'POST':
            # print('in POST', element_, element_.id)
            element_.delete()  #Удаление элемента корзины
            return HttpResponseRedirect('/adm_/?order=False')
        else:
            return HttpResponseRedirect(
                reverse_lazy('adm_element', args=[element_.id]))
Example #3
0
def amplifier(request, amp="0"):
    template = loader.get_template('bshop/gallery_amp.html')

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)
    else:
        for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username, cart__status=True)

    # query_string = ''
    # found_entries = None
    l = len(for_cart)
    for_cat_menu = Category.objects.all()
    # photos_ = Photo.objects.filter(is_alpha=True)[0:5]
    amp_ = get_object_or_404(Amplifier, id=amp)
    photos_ = Photo.objects.filter(amplifier=amp_).order_by('-is_alpha')
    print(photos_)
    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session,
               'cart_length': l, 'summ_in_cart': summ_in_cart(for_cart),
               'photos': photos_, 'amp': amp_}
    return HttpResponse(template.render(context, request))
Example #4
0
def menu(request, cat="0"):
    template = loader.get_template('bshop/in_catalog.html')
    for_cat_menu = Category.objects.all()
    name_ = ''
    for_content = {}

    for i in for_cat_menu:
        # str = i.get_absolute_url()
        if int(cat) == int(i.id):
            name_ = i.name
            for_content = Product.objects.filter(product__category=i.id)
    if not name_:
        return HttpResponseRedirect(reverse_lazy('index'))

    if request.method == 'GET':
        params_ = request.GET
        p = QueryDict('')
        if params_:
            p = params_.copy()
        if 'q' in p:
            # print("Search", request.GET['q'])
            query_string = p.get('q')
            entry_query = get_query(query_string, ['product__name', 'product__description', ])
            for_content = for_content.filter(entry_query)
            query_string = 'Результат поиска - ' + str(p.get('q'))
        else:
            query_string = name_

        f_ispreorder = p.get('ispreorder')
        if f_ispreorder == 'True' or f_ispreorder == 'False':
            for_content = for_content.filter(is_preorder=f_ispreorder)

        if 'sort' in p:
            sort_ = p.get('sort')
            if sort_ == 'PRICEUP':
                for_content = for_content.order_by('cost')
            if sort_ == 'PRICEDOWN':
                for_content = for_content.order_by('-cost')
            if sort_ == 'AVIALABLE':
                for_content = for_content.order_by('is_preorder')

    if not request.user.is_authenticated():
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)
    else:
        for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username, cart__status=True)
    l = len(for_cart)
    category_ = get_object_or_404(Category, id=cat)
    photos_ = get_list_or_404(Photo, product_in_time__category=category_.id, is_alpha=True)[0:4]

    # photos_ = Photo.objects.all()[0:4]
    context = {'menu': for_cat_menu, 'path': request.path, 'content': for_content, 'name': name_, 'catalog_id': cat,
               'session': request.session, 'cart_length': l, 'summ_in_cart': summ_in_cart(for_cart),
               'query_string': query_string,'photos': photos_, 'p': p, 'sort': Product.by_sort}
    return HttpResponse(template.render(context, request))
Example #5
0
def account(request):

    for_cat_menu = Category.objects.all()
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse_lazy('index'))
    else:
        for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username, cart__status=True)
        client_ = get_object_or_404(Client, user__username=request.user.username)
        data = {'firstname': client_.user.first_name, 'lastname': client_.user.last_name,
                'middlename': client_.middle_name,
                'tel': client_.tel, 'address': client_.address}
        form_ = UpdateForm(data)
    l = len(for_cart)
    if request.method == 'POST':
         form_ = UpdateForm(request.POST)
         if form_.is_valid():
            c = get_object_or_404(Client, user__username=request.user.username)
            u = request.user
            u.first_name = form_.cleaned_data.get('firstname')
            u.last_name = form_.cleaned_data.get('lastname')
            u.save()
            c.address = form_.cleaned_data.get('address')
            c.middle_name = form_.cleaned_data.get('middlename')
            c.tel = form_.cleaned_data.get('tel')
            c.save()
            if form_.cleaned_data.get('password_re') or form_.cleaned_data.get('password_re'):
                # print('password user', form_.cleaned_data.get('old_password'), u.password)
                if check_password(form_.cleaned_data.get('old_password'), u.password):
                    if form_.cleaned_data.get('password_re') == form_.cleaned_data.get('password_re2'):
                        try:
                            u.password = make_password(form_.cleaned_data.get('password_re'))
                            u.save()
                        except:
                            form_.add_error(field=None,
                                            error=ValidationError(
                                                'Возникла ошибка при сохранении нового пароля, обратитесь к администратору',
                                                code='invalid'))
                    else:
                        form_.add_error(field=None,
                                        error=ValidationError(
                                            'Введенные новые пароли пользователя не совпадают', code='invalid'))
                else:
                    form_.add_error(field=None,
                                    error=ValidationError(
                                        'Неверно указан текущий пароль пользователя',
                                        code='invalid'))


    template = loader.get_template('bshop/account.html')
    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session,
               'cart_length':l, 'summ_in_cart': summ_in_cart(for_cart),'form': form_}
    return HttpResponse(template.render(context, request))
Example #6
0
def my_register(request, next_='/'):

    form_ = RegisterForm()
    for_cat_menu = Category.objects.all()
    if ('next' in request.GET) and request.GET['next'].strip():
        next_ = request.GET['next']

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        # session = request.session['key']
        # print(request.session['last_date'], session)
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)

    else:

        return HttpResponseRedirect(reverse_lazy('index'))
    l = len(for_cart)

    if request.method == 'POST':
        form_ = RegisterForm(request.POST)
        if form_.is_valid():
            form_.save_user()
            user_ = form_.cleaned_data['login']
            password_ = form_.cleaned_data['password']
            user = authenticate(username=user_, password=password_)
            if user is not None:
                add_to_cart(for_cart, user)
                login(request, user)
                to = [form_.cleaned_data['email']]
                from_email = settings.DEFAULT_FROM_EMAIL
                subject_ = 'Регистрация на сайте'
                text_content = render_to_string('bshop/email/register.txt', {'first_name': form_.cleaned_data['firstname'],
                                                                              'username': form_.cleaned_data['login'],
                                                                              'password': form_.cleaned_data['password']})
                html_content = render_to_string('bshop/email/register.html', {'first_name': form_.cleaned_data['firstname'],
                                                                              'username': form_.cleaned_data['login'],
                                                                               'password': form_.cleaned_data['password']})
                # print(to, from_email, subject_, text_content, html_content)

                send_email(to, from_email, subject_, text_content, html_content)
                return HttpResponseRedirect(next_)
            else:
                pass
    template = loader.get_template('bshop/register.html')
    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session, 'form':form_, 'next': next_,
               'cart_length': l, 'summ_in_cart': summ_in_cart(for_cart), 'next': next_, 'form': form_}
    return HttpResponse(template.render(context, request))
Example #7
0
def index(request):
    template = loader.get_template('bshop/content.html')

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)
    else:
        for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username, cart__status=True)

    # query_string = ''
    # found_entries = None
    l = len(for_cart)
    for_cat_menu = Category.objects.all()
    photos_ = Photo.objects.filter(is_alpha=True)[0:5]
    # print(photos_)

    if request.method == 'GET':
        params_ = request.GET
        p = QueryDict('')
        if params_:
            p = params_.copy()
        if 'q' in p:
            # print("Search", request.GET['q'])
            query_string = p.get('q')
            entry_query = get_query(query_string, ['product__name', 'product__description', ])
            found_entries = Product.objects.filter(entry_query)
            query_string = 'Результат поиска - ' + str(p.get('q'))
        else:
            query_string = 'Последнее добавленное '
            found_entries = Product.objects.filter()
        f_ispreorder = p.get('ispreorder')
        if f_ispreorder == 'True' or f_ispreorder == 'False':
            found_entries = found_entries.filter(is_preorder=f_ispreorder)
        if 'sort' in p:
            sort_ = p.get('sort')
            if sort_ == 'PRICEUP':
                found_entries = found_entries.order_by('cost')
            if sort_ == 'PRICEDOWN':
                found_entries = found_entries.order_by('-cost')
            if sort_ == 'AVIALABLE':
                found_entries = found_entries.order_by('is_preorder')

    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session,
               'cart_length': l, 'summ_in_cart': summ_in_cart(for_cart), 'query_string': query_string,
               'found_entries': found_entries, 'photos': photos_, 'p': p, 'sort': Product.by_sort}
    return HttpResponse(template.render(context, request))
Example #8
0
def admin_client(request, client="0"):
    permission_req_ = 'shop.change_order'
    if not request.user.has_perm(permission_req_):
        raise Http404()
    else:
        for_cat_menu = Category.objects.all()
        for_cart = CartElement.objects.filter(
            cart__owner__user__username=request.user.username,
            cart__status=True)
        l = len(for_cart)
        clients_ = Client.objects.all()
        client_ = get_object_or_404(Client, id=client)
        orders_client = Order.objects.filter(list__owner__id=client_.id)
        if request.method == 'GET':
            p = request.GET
            page = p.get('page')
            paginator = Paginator(clients_, 20)
            try:
                clients_on_page = paginator.page(page)
            except PageNotAnInteger:
                clients_on_page = paginator.page(1)
            except EmptyPage:
                clients_on_page = paginator.page(paginator.num_pages)
            summ_ = 0
            for i in orders_client:
                summ_ += i.list.summ
            template = loader.get_template('bshop/admin_client.html')
            context = {
                'menu': for_cat_menu,
                'request': request,
                'path': request.path,
                'user': request.user,
                'session': request.session,
                'cart_length': l,
                'summ_in_cart': summ_in_cart(for_cart),
                'orders': orders_client,
                'client': client_,
                'summ': summ_,
                'clients': clients_on_page
            }

            return HttpResponse(template.render(context, request))
        else:
            return HttpResponseRedirect(
                reverse_lazy('adm_client', args=[client_.id]))
Example #9
0
def my_login(request, next_='/'):
    form_ = LoginForm
    for_cat_menu = Category.objects.all()

    if ('next' in request.GET) and request.GET['next'].strip():
        next_ = request.GET['next']

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        # session = request.session['key']
        # print(request.session['last_date'], session)
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)

    else:
        return HttpResponseRedirect(reverse_lazy('index'))
    l = len(for_cart)
    if request.method == 'POST':
        if request.is_ajax():
            # print('In ajax ', json.loads(request.body.decode('utf-8')))
            in_data = json.loads(request.body.decode('utf-8'))
            # print(in_data)
            form_ = LoginForm(data=in_data)
            # print('form - ', form_)
            user_ = in_data['login']
            password_ = in_data['password']
            # print(user_, password_)
            user = authenticate(username=user_, password=password_)
            if user is not None:
                add_to_cart(for_cart, user)
                login(request, user)
                response_data = {'errors': form_.errors, 'success_url': force_text(next_)}
                return HttpResponse(json.dumps(response_data), content_type="application/json")
            else:
                # print('form is invalid', form_)
                response_data = {'errors': form_.errors, 'success_url': force_text(next_)}
                return HttpResponse(json.dumps(response_data), content_type="application/json")

    template = loader.get_template('bshop/login_ajax.html')
    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session,
               'cart_length':l, 'summ_in_cart': summ_in_cart(for_cart), 'next': next_, 'form': form_}
    return HttpResponse(template.render(context, request))
Example #10
0
def about(request):

    for_cat_menu = Category.objects.all()

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)

    else:
        for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username, cart__status=True)
    l = len(for_cart)
    template = loader.get_template('bshop/about.html')
    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session,
               'cart_length':l, 'summ_in_cart': summ_in_cart(for_cart)}
    return HttpResponse(template.render(context, request))
Example #11
0
def order(request, order = '0'):
    template = loader.get_template('bshop/order.html')
    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        order_ = get_object_or_404(Order, list__key=request.session['key'], id=order)
        for_order = CartElement.objects.filter(cart__id=order_.list.id)
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)

    else:
        order_ = get_object_or_404(Order,list__owner__user__username=request.user.username, id=order)
        for_order = CartElement.objects.filter(cart__id=order_.list.id)
        for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username, cart__status=True)
    l = len(for_cart)
    for_cat_menu = Category.objects.all()
    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session, 'order': order_, 'positions': for_order,
               'cart_length': l, 'summ_in_cart': summ_in_cart(for_cart)}

    return HttpResponse(template.render(context, request))
Example #12
0
def gallery(request):
    template = loader.get_template('bshop/gallery.html')

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)
    else:
        for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username, cart__status=True)

    # query_string = ''
    # found_entries = None
    l = len(for_cart)
    for_cat_menu = Category.objects.all()
    # photos_ = Photo.objects.filter(is_alpha=True)[0:5]
    photos_ = Photo.objects.filter(amplifier__name__isnull=False, is_alpha=True)[0:5]


    if request.method == 'GET':
        params_ = request.GET
        p = QueryDict('')
        if params_:
            p = params_.copy()
        if 'q' in p:
            # print("Search", request.GET['q'])
            query_string = p.get('q')
            entry_query = get_query(query_string, ['name', 'description', ])
            found_entries = Amplifier.objects.filter(entry_query)
            query_string = 'Результат поиска - ' + str(p.get('q'))
        else:
            query_string = 'Галерея усилителей '
            found_entries = Amplifier.objects.filter()
    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session,
               'cart_length': l, 'summ_in_cart': summ_in_cart(for_cart), 'query_string': query_string,
               'found_entries': found_entries, 'photos': photos_, 'p': p}
    return HttpResponse(template.render(context, request))
Example #13
0
def order(request, order='0'):
    template = loader.get_template('bshop/order.html')
    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        order_ = get_object_or_404(Order,
                                   list__key=request.session['key'],
                                   id=order)
        for_order = CartElement.objects.filter(cart__id=order_.list.id)
        for_cart = CartElement.objects.filter(cart__key=request.session['key'],
                                              cart__status=True)

    else:
        order_ = get_object_or_404(
            Order, list__owner__user__username=request.user.username, id=order)
        for_order = CartElement.objects.filter(cart__id=order_.list.id)
        for_cart = CartElement.objects.filter(
            cart__owner__user__username=request.user.username,
            cart__status=True)
    l = len(for_cart)
    for_cat_menu = Category.objects.all()
    context = {
        'menu': for_cat_menu,
        'path': request.path,
        'user': request.user,
        'session': request.session,
        'order': order_,
        'positions': for_order,
        'cart_length': l,
        'summ_in_cart': summ_in_cart(for_cart)
    }

    return HttpResponse(template.render(context, request))
Example #14
0
def cart(request):

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        # session = request.session['key']
        # print(request.session['last_date'], session)
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)

    else:
        for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username, cart__status=True)
    l = len(for_cart)
    all_product_not_archive = True
    data_ = dict()
    formset = []
    form = CommentForm()
    if l:
        """form_data = {
            'form-TOTAL_FORMS': str(l),
            'form-INITIAL_FORMS:': str(l),
            'form-MAX_NUM_FORMS': str(l),
        }"""
        CartFormSet = formset_factory(CartForm, max_num=l, can_delete=True)
        if request.method == 'POST':
            formset = CartFormSet(request.POST, request.FILES)
            if formset.is_valid():
                # print('Update cart')
                on_delete = False
                for i in range(len(for_cart)):
                    # print(for_cart[i].quantity, for_cart[i].id, formset[i].cleaned_data['quantity'])
                    if (for_cart[i].quantity != formset[i].cleaned_data['quantity']):
                        # print(for_cart[i].quantity, formset[i].cleaned_data['quantity'])
                        try:
                            cart_element = CartElement.objects.get(id=for_cart[i].id)
                            product = get_object_or_404(Product, id=cart_element.product.id)
                            if cart_element.is_preorder:
                                # print('preorder change')
                                cart_element.quantity = formset[i].cleaned_data['quantity']
                                cart_element.save()
                            elif not cart_element.is_preorder:
                                # print('Edit in stock')
                                if cart_element.quantity > formset[i].cleaned_data['quantity']:
                                    # print('Is in dec quantity', cart_element.quantity, formset[i].cleaned_data['quantity'])
                                    # print('Old - ', product.quantity_in_reserv)
                                    product.quantity_in_reserv -= int(cart_element.quantity) - int(formset[i].cleaned_data['quantity'])
                                    if product.quantity_in_reserv < 0:
                                        product.quantity_in_reserv = 0
                                    product.save()
                                    # print('New - ', product.quantity_in_reserv)
                                    cart_element.quantity = formset[i].cleaned_data['quantity']
                                else:
                                    # print('Is in add quantity')
                                    if (product.quantity - product.quantity_in_reserv) >= (formset[i].cleaned_data['quantity'] - cart_element.quantity):
                                        # print('Is Ok in rexize quantity')
                                        product.quantity_in_reserv += formset[i].cleaned_data['quantity'] - cart_element.quantity
                                        cart_element.quantity = formset[i].cleaned_data['quantity']
                                        product.save()

                                cart_element.save()
                        except:
                            pass
                    if formset[i].cleaned_data['DELETE']:
                        try:
                            cart_element = CartElement.objects.get(id=for_cart[i].id)
                            product = get_object_or_404(Product, id=cart_element.product.id)
                            # print(product)
                            if not product.is_preorder and (product.quantity_in_reserv - cart_element.quantity) >= 0:
                                product.quantity_in_reserv -= cart_element.quantity
                                product.save()
                            cart_element.delete()
                            on_delete = True
                        except:
                            pass

                if on_delete:
                    return HttpResponseRedirect(reverse_lazy('cart'))
            if 'Order' in request.POST:
                # print('Is Place order')
                # Переполучаем корзину, т.к. она могла обновиться на форме и обработана выше.
                if not request.user.is_authenticated():
                    for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)
                else:
                    for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username,
                                                          cart__status=True)
                # Проверки на наличие в корзине товара со статусом не доступен к заказу (обход запреда нажатия html кнопок)
                for i in for_cart:
                    if not i.product.is_not_arhive:
                        return HttpResponseRedirect(reverse_lazy('cart'))  #Если есть, редиректим на страницу корзины

                form = CommentForm(request.POST)
                if form.is_valid():
                    comment = form.cleaned_data['comment']
                if request.user.is_authenticated:
                    cart_ = Cart.objects.filter(owner__user__username=request.user.username, status=True)
                    if cart_:
                        for item in cart_:
                            if item.status:
                                cart_ = item
                                break  # Пока берем первую запись не являющуюся заказом

                        new_order = Order(list=cart_, datetime=datetime.datetime.now(), status='NEW', comment=comment)
                        new_order.save()
                        cart_.status = False
                        cart_.summ = summ_in_cart(for_cart)
                        cart_.save()
                        # print(" Sending mail")
                        for_order = CartElement.objects.filter(cart__id=new_order.list.id)
                        user = request.user
                        to = [user.email]
                        from_email = settings.DEFAULT_FROM_EMAIL
                        subject_ = 'Новый заказ - ' + str(new_order.id)
                        text_content = render_to_string('bshop/email/neworder.txt',
                                                        {'first_name': request.user.first_name,
                                                         'username': user.username,
                                                         'summ_in_cart': summ_in_cart(for_cart),
                                                         'order': new_order,
                                                         'positions': for_order})
                        html_content = render_to_string('bshop/email/neworder.html',
                                                        {'first_name': request.user.first_name,
                                                         'username': user.username,
                                                         'summ_in_cart': summ_in_cart(for_cart),
                                                         'order': new_order,
                                                         'positions': for_order})
                        # print(to, from_email, subject_, html_content)

                        send_email(to, from_email, subject_, text_content, html_content)

                        to = [settings.ADMIN_EMAIL]
                        send_email(to, from_email, subject_, text_content, html_content)

                        return HttpResponseRedirect(reverse_lazy('orders'))
                else:
                    # Нужно авторизовать или зарегистрировать пользователя, после чего добавить ему товар из сессии
                    # и отправить на страницу оформления заказа
                    # Скорее всего решается требованием работы со страницей потверждения заказа только автотизованного пользователя
                    return HttpResponseRedirect(reverse_lazy('login'))

            return HttpResponseRedirect(reverse_lazy('cart'))

        else:
            init_ = []
            for i in for_cart:
                if not i.product.is_not_arhive:
                    all_product_not_archive = False
                init_.append({'quantity': i.quantity})
            # formset = CartFormSet(form_data, initial=init_)
            formset = CartFormSet(initial=init_)
        data_ = dict(pairs=zip(for_cart, formset))


    template = loader.get_template('bshop/cart.html')
    for_cat_menu = Category.objects.all()
    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session,
               'cart_length':l, 'summ_in_cart': summ_in_cart(for_cart), 'formset': formset, 'data': data_, 'form': form,
               'alert_archive': all_product_not_archive}

    return HttpResponse(template.render(context, request))
Example #15
0
def admin_order(request, order="0"):
    permission_req_ = 'shop.change_order'
    if not request.user.has_perm(permission_req_):
        raise Http404()
    else:
        for_cat_menu = Category.objects.all()
        for_cart = CartElement.objects.filter(
            cart__owner__user__username=request.user.username,
            cart__status=True)
        l = len(for_cart)
        order_ = get_object_or_404(Order, id=order)
        for_order = CartElement.objects.filter(cart__id=order_.list.id)
        client_ = order_.list.owner
        pre_quantity_list = []
        for item in for_order:
            if item.is_preorder:
                sum_ = CartElement.objects.filter(
                    product__id=item.product.id,
                    is_preorder=True,
                    is_calculate=False,
                    cart__status='False').exclude(
                        cart__order__status='CLOSE').aggregate(Sum('quantity'))
                pre_quantity_list.append((item, sum_['quantity__sum']))
            else:
                pre_quantity_list.append((item, 0))
        if request.method == 'GET':
            data = {
                'status': order_.status,
                'prepay': order_.prepay,
                'relay_free': order_.relay_free,
                'total': order_.total,
                'type_of_dispatch': order_.type_of_dispatch,
                'track_number': order_.track_number,
                'linked_orders': order_.linked_orders
            }
            form_ = EditOrderForm(data)
            template = loader.get_template('bshop/admin_order.html')
            context = {
                'menu': for_cat_menu,
                'request': request,
                'path': request.path,
                'user': request.user,
                'session': request.session,
                'cart_length': l,
                'summ_in_cart': summ_in_cart(for_cart),
                'order': order_,
                'positions': for_order,
                'client': client_,
                'form': form_,
                'pre_quantity': pre_quantity_list
            }

            return HttpResponse(template.render(context, request))
        elif request.method == 'POST':
            form_ = EditOrderForm(request.POST)
            if form_.is_valid():
                change_status = 'False'
                if order_.status != form_.cleaned_data['status']:
                    change_status = True
                order_.status = form_.cleaned_data['status']
                order_.prepay = form_.cleaned_data['prepay']
                order_.relay_free = form_.cleaned_data['relay_free']
                order_.total = form_.cleaned_data['total']
                order_.type_of_dispatch = form_.cleaned_data[
                    'type_of_dispatch']
                order_.track_number = form_.cleaned_data['track_number']
                order_.linked_orders = form_.cleaned_data['linked_orders']
                order_.save()
                if order_.status in ('PRE', 'INJOB', 'PAY', 'CLOSE'):
                    for i in for_order:
                        if i.is_preorder == False and i.is_calculate == False:
                            if i.product.quantity > i.quantity:
                                i.product.quantity = int(
                                    i.product.quantity) - int(i.quantity)
                                i.product.quantity_in_reserv = int(
                                    i.product.quantity_in_reserv) - int(
                                        i.quantity)
                                # print('calculate to ', i.product.quantity, i.product.quantity_in_reserv)
                                i.is_calculate = True
                                i.product.save()
                                i.save()
                if order_.status in ('CLOSE', ):
                    for i in for_order:
                        if i.is_preorder == True and i.is_calculate == False:
                            i.is_calculate = True
                            i.save()
                if change_status == True:
                    if client_.user.username != 'None':
                        to = [client_.user.email]
                        first_name_ = client_.user.first_name
                    else:
                        to = [order_.person.email]
                        first_name_ = order_.person.first_name
                    from_email = settings.DEFAULT_FROM_EMAIL
                    subject_ = 'Изменение статуса заказа ' + str(order_.id)
                    text_content = render_to_string(
                        'bshop/email/changeorder.txt', {
                            'first_name': first_name_,
                            'summ_in_cart': order_.list.summ,
                            'order': order_,
                            'positions': for_order
                        })
                    html_content = render_to_string(
                        'bshop/email/changeorder.html', {
                            'first_name': first_name_,
                            'summ_in_cart': order_.list.summ,
                            'order': order_,
                            'positions': for_order
                        })
                    send_email(to, from_email, subject_, text_content,
                               html_content)

                return HttpResponseRedirect(reverse_lazy('adm_'))

            return HttpResponseRedirect(
                reverse_lazy('adm_order', args=[order_.id]))
        else:
            return HttpResponseRedirect(
                reverse_lazy('adm_order', args=[order_.id]))
Example #16
0
def account(request):

    for_cat_menu = Category.objects.all()
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse_lazy('index'))
    else:
        for_cart = CartElement.objects.filter(
            cart__owner__user__username=request.user.username,
            cart__status=True)
        client_ = get_object_or_404(Client,
                                    user__username=request.user.username)
        data = {
            'firstname': client_.user.first_name,
            'lastname': client_.user.last_name,
            'middlename': client_.middle_name,
            'tel': client_.tel,
            'address': client_.address
        }
        form_ = UpdateForm(data)
    l = len(for_cart)
    if request.method == 'POST':
        form_ = UpdateForm(request.POST)
        if form_.is_valid():
            c = get_object_or_404(Client, user__username=request.user.username)
            u = request.user
            u.first_name = form_.cleaned_data.get('firstname')
            u.last_name = form_.cleaned_data.get('lastname')
            u.save()
            c.address = form_.cleaned_data.get('address')
            c.middle_name = form_.cleaned_data.get('middlename')
            c.tel = form_.cleaned_data.get('tel')
            c.save()
            if form_.cleaned_data.get('password_re') or form_.cleaned_data.get(
                    'password_re'):
                # print('password user', form_.cleaned_data.get('old_password'), u.password)
                if check_password(form_.cleaned_data.get('old_password'),
                                  u.password):
                    if form_.cleaned_data.get(
                            'password_re') == form_.cleaned_data.get(
                                'password_re2'):
                        try:
                            u.password = make_password(
                                form_.cleaned_data.get('password_re'))
                            u.save()
                        except:
                            form_.add_error(
                                field=None,
                                error=ValidationError(
                                    'Возникла ошибка при сохранении нового пароля, обратитесь к администратору',
                                    code='invalid'))
                    else:
                        form_.add_error(
                            field=None,
                            error=ValidationError(
                                'Введенные новые пароли пользователя не совпадают',
                                code='invalid'))
                else:
                    form_.add_error(
                        field=None,
                        error=ValidationError(
                            'Неверно указан текущий пароль пользователя',
                            code='invalid'))

    template = loader.get_template('bshop/account.html')
    context = {
        'menu': for_cat_menu,
        'path': request.path,
        'user': request.user,
        'session': request.session,
        'cart_length': l,
        'summ_in_cart': summ_in_cart(for_cart),
        'form': form_
    }
    return HttpResponse(template.render(context, request))
Example #17
0
def product(request, cat="0", prod="0"):
    template = loader.get_template('bshop/product.html')
    for_cat_menu = Category.objects.all()
    name_ = ''
    for i in for_cat_menu:
        if int(cat) == int(i.id):
            name_ = i.name
    if not name_:
        return HttpResponseRedirect(reverse_lazy('index'))
    product_ = get_object_or_404(Product, id=prod)
    photos_ = Photo.objects.filter(product_in_time=product_.product).order_by('-is_alpha')
    jointly_ = get_jointly(prod)
    drawings_ = Drawing.objects.filter(product_in_time=product_.product)
    # print(drawings_)
    if not request.user.is_authenticated():
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)
    else:
        for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username, cart__status=True)
    l = len(for_cart)
    # обновляем сумму заказа
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            if request.user.is_authenticated:
                owner_ = get_object_or_404(Client, user__username=request.user.username)
                quantity_ = int(form.cleaned_data['quantity'])
                product_ = get_object_or_404(Product, id=prod, is_not_arhive=True)
                # cartElement_ = CartElement.objects.create(product=product_, quantity=quantity_, is_preorder=False)
                cart_ = Cart.objects.filter(owner__user__username=request.user.username, status=True)
                if not cart_:
                    cart_ = Cart(owner=owner_, datetime=datetime.datetime.now())
                    cart_.save()
                else:
                    for item in cart_:
                        if item.status:
                            cart_ = item
                            break                   # Пока берем первую запись не являющуюся заказом
                # Провярzем на наличие позиции в корзине у этого пользователя
                cartElement_= CartElement.objects.filter(product=product_, cart__id=cart_.id)
                # print('found', cartElement_)
                if not cartElement_:
                    if product_.is_preorder:
                        cartElement_ = CartElement.objects.create(product=product_, quantity=quantity_,
                                                                  is_preorder=True)
                        cart_.cartElement.add(cartElement_)
                        cart_.save()
                    elif product_.is_in_stock and (product_.quantity - product_.quantity_in_reserv) >= quantity_:
                        cartElement_ = CartElement.objects.create(product=product_, quantity=quantity_,
                                                                  is_preorder=False)
                        # product_.quantity -= quantity_
                        product_.quantity_in_reserv += quantity_
                        product_.save()
                        cart_.cartElement.add(cartElement_)
                        cart_.save()
                    else:
                        # print('Not Adding in stok < reserv', product_.quantity, product_.quantity_in_reserv)
                        pass


                else:
                    # Ориентируемся что пока у пользователя только одна текущая корзина
                    if product_.is_preorder:
                        if cartElement_[0].is_preorder:
                            cartElement_[0].quantity = cartElement_[0].quantity + quantity_
                            cartElement_[0].save()
                    elif not cartElement_[0].is_preorder and (product_.quantity - product_.quantity_in_reserv) >= quantity_:
                        if not cartElement_[0].is_preorder:
                            # product_.quantity -= quantity_
                            product_.quantity_in_reserv += quantity_
                            product_.save()
                            cartElement_[0].quantity = cartElement_[0].quantity + quantity_
                            cartElement_[0].save()
                    else:
                        # print('Not Adding 2 in stok < reserv', product_.quantity, product_.quantity_in_reserv)
                        pass


            else:
                owner_ = get_object_or_404(Client, user__username='******')
                quantity_ = int(form.cleaned_data['quantity'])
                product_ = get_object_or_404(Product, id=prod, is_not_arhive=True)
                # cartElement_ = CartElement.objects.create(product=product_, quantity=quantity_, is_preorder=False)
                cart_ = Cart.objects.filter(owner__user__username='******', key=request.session['key'], status=True)
                if not cart_:
                    cart_ = Cart(owner=owner_, datetime=datetime.datetime.now(), key=request.session['key'])
                    cart_.save()
                else:
                    for item in cart_:
                        if item.status:
                            cart_ = item
                            break                   # Пока берем первую запись не являющуюся заказом
                # Провярzем на наличие позиции в корзине у этого пользователя
                cartElement_ = CartElement.objects.filter(product=product_,
                                                          cart__id=cart_.id)
                # print('found', cartElement_)
                if not cartElement_:
                    if product_.is_preorder:
                        cartElement_ = CartElement.objects.create(product=product_, quantity=quantity_, is_preorder=True)
                        cart_.cartElement.add(cartElement_)
                        cart_.save()
                    elif product_.is_in_stock and (product_.quantity - product_.quantity_in_reserv) >= quantity_:
                        cartElement_ = CartElement.objects.create(product=product_, quantity=quantity_,
                                                                  is_preorder=False)
                        # product_.quantity -= quantity_
                        product_.quantity_in_reserv += quantity_
                        product_.save()
                        cart_.cartElement.add(cartElement_)
                        cart_.save()
                    else:
                        # print('Not Adding in stok < reserv', product_.quantity, product_.quantity_in_reserv)
                        pass
                else:
                    # Ориентируемся что пока у пользователя только одна текущая корзина
                    if product_.is_preorder:
                        if cartElement_[0].is_preorder:
                            cartElement_[0].quantity = cartElement_[0].quantity + quantity_
                            cartElement_[0].quantity = cartElement_[0].quantity + quantity_
                            cartElement_[0].save()
                    elif not cartElement_[0].is_preorder and (product_.quantity - product_.quantity_in_reserv) >= quantity_:
                        if not cartElement_[0].is_preorder:
                            # product_.quantity -= quantity_
                            product_.quantity_in_reserv += quantity_
                            product_.save()
                            cartElement_[0].quantity = cartElement_[0].quantity + quantity_
                            cartElement_[0].save()
                    else:
                        # print('Not Adding 2 in stok < reserv', product_.quantity, product_.quantity_in_reserv)
                        pass
        return HttpResponseRedirect(request.path)
    else:
        form = ProductForm()
        if product_.is_in_stock and (product_.quantity_in_reserv >= product_.quantity):
            is_missing_quantity = True
        else:
            is_missing_quantity = False

    context = {'menu': for_cat_menu, 'path': request.path, 'prod': product_, 'name': name_, 'catalog_id': cat,
             'form': form, 'session': request.session, 'cart_length': l, 'summ_in_cart': summ_in_cart(for_cart),
             'photos': photos_, 'is_missing': is_missing_quantity, 'jointly': jointly_, 'drawings': drawings_}
    return HttpResponse(template.render(context, request))
Example #18
0
def menu(request, cat="0"):
    template = loader.get_template('bshop/in_catalog.html')
    for_cat_menu = Category.objects.all()
    name_ = ''
    for_content = {}

    for i in for_cat_menu:
        # str = i.get_absolute_url()
        if int(cat) == int(i.id):
            name_ = i.name
            for_content = Product.objects.filter(product__category=i.id)
    if not name_:
        return HttpResponseRedirect(reverse_lazy('index'))

    if request.method == 'GET':
        params_ = request.GET
        p = QueryDict('')
        if params_:
            p = params_.copy()
        if 'q' in p:
            # print("Search", request.GET['q'])
            query_string = p.get('q')
            entry_query = get_query(query_string, [
                'product__name',
                'product__description',
            ])
            for_content = for_content.filter(entry_query)
            query_string = 'Результат поиска - ' + str(p.get('q'))
        else:
            query_string = name_

        f_ispreorder = p.get('ispreorder')
        if f_ispreorder == 'True' or f_ispreorder == 'False':
            for_content = for_content.filter(is_preorder=f_ispreorder)

        if 'sort' in p:
            sort_ = p.get('sort')
            if sort_ == 'PRICEUP':
                for_content = for_content.order_by('cost')
            if sort_ == 'PRICEDOWN':
                for_content = for_content.order_by('-cost')
            if sort_ == 'AVIALABLE':
                for_content = for_content.order_by('is_preorder')

    if not request.user.is_authenticated():
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'],
                                              cart__status=True)
    else:
        for_cart = CartElement.objects.filter(
            cart__owner__user__username=request.user.username,
            cart__status=True)
    l = len(for_cart)
    category_ = get_object_or_404(Category, id=cat)
    photos_ = get_list_or_404(Photo,
                              product_in_time__category=category_.id,
                              is_alpha=True)[0:4]

    # photos_ = Photo.objects.all()[0:4]
    context = {
        'menu': for_cat_menu,
        'path': request.path,
        'content': for_content,
        'name': name_,
        'catalog_id': cat,
        'session': request.session,
        'cart_length': l,
        'summ_in_cart': summ_in_cart(for_cart),
        'query_string': query_string,
        'photos': photos_,
        'p': p,
        'sort': Product.by_sort
    }
    return HttpResponse(template.render(context, request))
Example #19
0
def restorePwd(request):

    for_cat_menu = Category.objects.all()
    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)
    else:
        for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username, cart__status=True)
    if ('key' in request.GET) and request.GET['key'].strip():
        key_ = request.GET['key']
        # print("Get Change Password for key", key_)
    else:
        return HttpResponseRedirect(reverse_lazy('login'))

    l = len(for_cart)
    form_ = ChangePasswordForm()
    isChangeOk = False
    if request.method == 'POST':
        if key_:
            # print("POST Change Password for key", key_)
            form_ = ChangePasswordForm(request.POST)
            if form_.is_valid():
                # print('Edit ')
                try:
                    a = uuid.UUID(key_)
                    # print('Is valid uuid', a)
                    k = Key.objects.filter(key=key_)[0]
                    # print(k)
                    # k = get_object_or_404(Key, )
                    if k and not k.isUsed:
                        if timezone.now() < k.datetime + datetime.timedelta(hours=24):
                            u = get_object_or_404(User, username=k.login)
                            # print(u, k)
                            try:
                                u.password = make_password(form_.cleaned_data.get('password'))
                                u.save()
                                k.isUsed = True
                                k.save()
                                isChangeOk = True
                                # return HttpResponseRedirect(reverse_lazy('login'))
                            except:
                                # print("Passsword change error")
                                form_.add_error(field=None,
                                                error=ValidationError(
                                                    'Возникла ошибка при сохранении нового пароля, обратитесь к администратору',
                                                    code='invalid'))
                        else:
                            # print("Key key is expired")
                            form_.add_error(field=None,
                                            error=ValidationError('Срок действия ключа для восстановления пароля истек',
                                                                  code='invalid'))
                    else:
                        # print('key is used')
                        form_.add_error(field=None,
                                        error=ValidationError('Ключ для восстановления пароля уже использован',
                                                              code='invalid'))
                except:
                    # print('Is not valid uuid')
                    form_.add_error(field=None, error=ValidationError('Неверный формат ключа для восстановления пароля',
                                                                      code='invalid'))

    template = loader.get_template('bshop/restore_password.html')
    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session,
               'cart_length': l, 'summ_in_cart': summ_in_cart(for_cart), 'form': form_, 'key': key_, 'isChangeOk': isChangeOk}
    return HttpResponse(template.render(context, request))
Example #20
0
def my_register(request, next_='/'):

    form_ = RegisterForm()
    for_cat_menu = Category.objects.all()
    if ('next' in request.GET) and request.GET['next'].strip():
        next_ = request.GET['next']

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        # session = request.session['key']
        # print(request.session['last_date'], session)
        for_cart = CartElement.objects.filter(cart__key=request.session['key'],
                                              cart__status=True)

    else:

        return HttpResponseRedirect(reverse_lazy('index'))
    l = len(for_cart)

    if request.method == 'POST':
        form_ = RegisterForm(request.POST)
        if form_.is_valid():
            form_.save_user()
            user_ = form_.cleaned_data['login']
            password_ = form_.cleaned_data['password']
            user = authenticate(username=user_, password=password_)
            if user is not None:
                add_to_cart(for_cart, user)
                login(request, user)
                to = [form_.cleaned_data['email']]
                from_email = settings.DEFAULT_FROM_EMAIL
                subject_ = 'Регистрация на сайте'
                text_content = render_to_string(
                    'bshop/email/register.txt', {
                        'first_name': form_.cleaned_data['firstname'],
                        'username': form_.cleaned_data['login'],
                        'password': form_.cleaned_data['password']
                    })
                html_content = render_to_string(
                    'bshop/email/register.html', {
                        'first_name': form_.cleaned_data['firstname'],
                        'username': form_.cleaned_data['login'],
                        'password': form_.cleaned_data['password']
                    })
                # print(to, from_email, subject_, text_content, html_content)

                send_email(to, from_email, subject_, text_content,
                           html_content)
                return HttpResponseRedirect(next_)
            else:
                pass
    template = loader.get_template('bshop/register.html')
    context = {
        'menu': for_cat_menu,
        'path': request.path,
        'user': request.user,
        'session': request.session,
        'form': form_,
        'next': next_,
        'cart_length': l,
        'summ_in_cart': summ_in_cart(for_cart),
        'next': next_,
        'form': form_
    }
    return HttpResponse(template.render(context, request))
Example #21
0
def admin_catalog(request, cat="0"):
    permission_req_ = 'shop.change_order'
    if not request.user.has_perm(permission_req_):
        raise Http404()
    else:
        for_cat_menu = Category.objects.all()
        name_ = ''
        for i in for_cat_menu:
            # str = i.get_absolute_url()
            if int(cat) == int(i.id):
                name_ = i.name
                product_ = Product.objects.filter(product__category=i.id)
        if not name_:
            return HttpResponseRedirect(reverse_lazy('adm_'))

        for_cart = CartElement.objects.filter(
            cart__owner__user__username=request.user.username,
            cart__status=True)
        l = len(for_cart)
        params_ = request.GET
        if not params_:
            p = QueryDict()
        else:
            p = params_.copy()
        start_date_ = p.get('start_date')
        end_date_ = p.get('end_date')
        # print(start_date_, end_date_)
        init_ = {}
        if start_date_:
            init_['start_date'] = parse_date(start_date_)
        if end_date_:
            init_['end_date'] = parse_date(end_date_)
        form_ = DateTimeForm(initial=init_)

        orders_products_ = []
        amount = 0
        for item in product_:
            orders_ = []
            cartElements_ = CartElement.objects.filter(product__id=item.id)
            if start_date_:
                try:
                    start = parse_date(start_date_)
                    cartElements_ = cartElements_.filter(
                        cart__datetime__date__gte=start)
                except:
                    pass
            if end_date_:
                try:
                    end = parse_date(end_date_)
                    cartElements_ = cartElements_.filter(
                        datetime__date__lte=end)
                except:
                    pass
            if cartElements_:
                for el in cartElements_:
                    # Получить список корзин с данным товаром
                    cart_ = Cart.objects.filter(
                        cartElement=el.id).distinct().order_by('-datetime')
                    if cart_:
                        # print(cart_[0], cart_[0].status)
                        if cart_[0].status:  # Если корзина
                            # print ('is cart')
                            orders_.append((cart_[0], el))
                        else:  # Если заказ
                            # print('is order')
                            order_ = Order.objects.filter(
                                list__cartElement=el.id).distinct().order_by(
                                    '-datetime')
                            if order_:  # Если заказ не потерт
                                orders_.append((order_[0], el))
                            else:  # Если заказ стерт потерта
                                orders_.append((order_, el))
                    else:  # Если корзина потерта
                        orders_.append((cart_, el))
                total_quantity = cartElements_.aggregate(
                    Sum('quantity'))['quantity__sum']
                total_sum = total_quantity * item.cost
                amount += total_sum
                total_proceeds = total_quantity * (item.cost - item.outlay)
                # print('Add - ', item, orders_, cartElements_.aggregate(Sum('quantity'))['quantity__sum'])
                orders_products_.append(
                    (item, orders_, total_quantity, total_sum, total_proceeds))

        template = loader.get_template('bshop/admin_catalog_list.html')
        context = {
            'menu': for_cat_menu,
            'request': request,
            'path': request.path,
            'user': request.user,
            'session': request.session,
            'cart_length': l,
            'summ_in_cart': summ_in_cart(for_cart),
            'catalog_name': name_,
            'orders_products': orders_products_,
            'form': form_,
            'amount': amount
        }

        return HttpResponse(template.render(context, request))
Example #22
0
def admin_cart(request, cart="0"):
    permission_req_ = 'shop.change_order'
    if not request.user.has_perm(permission_req_):
        raise Http404()
    else:
        for_cat_menu = Category.objects.all()
        for_cart = CartElement.objects.filter(
            cart__owner__user__username=request.user.username,
            cart__status=True)
        l = len(for_cart)
        cart_ = get_object_or_404(Cart, id=cart)
        carts_ = CartElement.objects.filter(cart__id=cart_.id)
        client_ = cart_.owner
        pre_quantity_list = []

        for item in carts_:
            if item.is_preorder:
                sum_ = CartElement.objects.filter(
                    product__id=item.product.id,
                    is_preorder=True,
                    cart__status='False').exclude(
                        cart__order__status='CLOSE').aggregate(Sum('quantity'))
                # print(sum_)
                pre_quantity_list.append((item, sum_['quantity__sum']))
            else:
                pre_quantity_list.append((item, 0))
        if request.method == 'GET':
            data = {'status': cart_.status}
            form_ = EditCartForm(data)
            template = loader.get_template('bshop/admin_cart.html')
            context = {
                'menu': for_cat_menu,
                'request': request,
                'path': request.path,
                'user': request.user,
                'session': request.session,
                'cart_length': l,
                'summ_in_cart': summ_in_cart(for_cart),
                'cart': cart_,
                'positions': carts_,
                'client': client_,
                'form': form_,
                'pre_quantity': pre_quantity_list
            }

            return HttpResponse(template.render(context, request))

        elif request.method == 'POST':
            for i in carts_:
                if i.is_preorder == False:
                    if (int(i.product.quantity_in_reserv) -
                            int(i.quantity)) >= 0:
                        i.product.quantity_in_reserv = int(
                            i.product.quantity_in_reserv) - int(i.quantity)
                        i.product.save()
                # try:
                #     i.delete()          #Удаление элемента корзины
                # except:
                #    pass
            try:
                cart_.delete()  #Удаление самой корзины пользователя
            except:
                pass
            return HttpResponseRedirect('/adm_/?order=False')
        else:
            return HttpResponseRedirect(
                reverse_lazy('adm_cart', args=[cart_.id]))
Example #23
0
def admin_(request):
    permission_req_ = 'shop.change_order'
    # print(request.user.has_perm(permission_req_))

    if not request.user.has_perm(permission_req_):
        raise Http404()
    else:
        if request.method == 'GET':
            params_ = request.GET
            if not params_:
                p = QueryDict('order=True')
            elif 'order' not in params_:
                p = params_.copy()
                p['order'] = 'True'
            else:
                p = params_.copy()
            #print(p)
            f_order_ = p.get('order')
            f_status_ = p.get('status')
            f_ispreorder = p.get('ispreorder')
            page = p.get('page')
            start_date_ = p.get('start_date')
            end_date_ = p.get('end_date')
            # print(start_date_, end_date_)
            query_string = ''
            init_ = {}
            if start_date_:
                init_['start_date'] = parse_date(start_date_)
            if end_date_:
                init_['end_date'] = parse_date(end_date_)
            form_ = DateTimeForm(initial=init_)
            # print(form_)
            for_cat_menu = Category.objects.all()
            for_cart = CartElement.objects.filter(
                cart__owner__user__username=request.user.username,
                cart__status=True)
            l = len(for_cart)
            if f_order_ == 'True':
                if f_ispreorder:
                    if f_status_:
                        orders_ = Order.objects.filter(
                            list__cartElement__is_preorder=f_ispreorder,
                            list__status=False,
                            status=f_status_).distinct().order_by('-datetime')
                    else:
                        orders_ = Order.objects.filter(
                            list__cartElement__is_preorder=f_ispreorder,
                            list__status=False).distinct().order_by(
                                '-datetime')
                elif f_ispreorder == 'False':
                    if f_status_:
                        orders_ = Order.objects.filter(
                            list__cartElement__is_preorder=f_ispreorder,
                            list__status=False,
                            status=f_status_).distinct().order_by('-datetime')
                    else:
                        orders_ = Order.objects.filter(
                            list__cartElement__is_preorder=f_ispreorder,
                            list__status=False).distinct().order_by(
                                '-datetime')
                else:
                    if f_status_:
                        orders_ = Order.objects.filter(
                            list__status=False,
                            status=f_status_).distinct().order_by('-datetime')
                    else:
                        orders_ = Order.objects.filter(
                            list__status=False).distinct().order_by(
                                '-datetime')

                        # start_date_aware = datetime.combine(parse_date(start_date_), time())
                        # end_date_aware = datetime.combine(parse_date(end_date_), time())
                        # tz = pytz.timezone('Europe/Moscow')
                        # print(start_date_aware, end_date_aware)
                        # print(timezone.make_aware(start_date_aware, tz, is_dst=True))
                        # print(timezone.make_aware(end_date_aware, tz, is_dst=True))
                        # print(timezone.is_naive(parse_date(start_date_)))
                        # print(parse_date(start_date_), timezone.make_naive(parse_date(start_date_), timezone='Europe/Moscow'))
                if start_date_:
                    try:
                        start = parse_date(start_date_)
                        orders_ = orders_.filter(datetime__date__gte=start)
                    except:
                        pass
                if end_date_:
                    try:
                        end = parse_date(end_date_)
                        orders_ = orders_.filter(datetime__date__lte=end)
                    except:
                        pass
                if 'q' in p:
                    # print("Search", p.get('q'))
                    query_string = p.get('q')
                    entry_query = get_query(query_string, [
                        'linked_orders', 'track_number', 'comment',
                        'list__summ', 'list__owner__tel',
                        'list__owner__address', 'list__owner__middle_name',
                        'list__owner__user__username',
                        'list__owner__user__first_name',
                        'list__owner__user__last_name',
                        'list__owner__user__email',
                        'list__cartElement__product__product__name',
                        'list__cartElement__product__product__description',
                        'person__first_name', 'person__last_name',
                        'person__middle_name', 'person__address',
                        'person__tel', 'person__email'
                    ])
                    orders_ = orders_.filter(entry_query)
                paginator = Paginator(
                    orders_, 20)  # Количество отображаемых записей на странице
                try:
                    orders_on_page = paginator.page(page)
                except PageNotAnInteger:
                    orders_on_page = paginator.page(1)
                except EmptyPage:
                    orders_on_page = paginator.page(paginator.num_pages)
                summ_ = 0
                for i in orders_:
                    summ_ += i.list.summ
                template = loader.get_template('bshop/admin_orders.html')
                context = {
                    'menu': for_cat_menu,
                    'request': request,
                    'path': request.path,
                    'user': request.user,
                    'session': request.session,
                    'orders': orders_,
                    'cart_length': l,
                    'summ_in_cart': summ_in_cart(for_cart),
                    'orders': orders_on_page,
                    'p': p,
                    'status': Order.status_in_choices,
                    'summ': summ_,
                    'form': form_,
                    'count': paginator.count,
                    'query_string': query_string,
                }
            else:
                if f_ispreorder == 'True' or f_ispreorder == 'False':
                    carts_ = Cart.objects.filter(
                        cartElement__is_preorder=f_ispreorder,
                        status=True).distinct().order_by('-datetime')
                else:
                    carts_ = Cart.objects.filter(
                        status=True).order_by('-datetime')
                if start_date_:
                    try:
                        start = parse_date(start_date_)
                        carts_ = carts_.filter(datetime__date__gte=start)
                    except:
                        pass
                if end_date_:
                    try:
                        end = parse_date(end_date_)
                        carts_ = carts_.filter(datetime__date__lte=end)
                    except:
                        pass
                if 'q' in p:
                    # print("Search", p.get('q'))
                    query_string = p.get('q')
                    entry_query = get_query(query_string, [
                        'summ',
                        'owner__tel',
                        'owner__address',
                        'owner__middle_name',
                        'owner__user__username',
                        'owner__user__first_name',
                        'owner__user__last_name',
                        'owner__user__email',
                        'cartElement__product__product__name',
                        'cartElement__product__product__description',
                    ])
                    carts_ = carts_.filter(entry_query)

                paginator = Paginator(
                    carts_, 20)  # Количество отображаемых записей на странице

                try:
                    carts_on_page = paginator.page(page)
                except PageNotAnInteger:
                    carts_on_page = paginator.page(1)
                except EmptyPage:
                    carts_on_page = paginator.page(paginator.num_pages)
                template = loader.get_template('bshop/admin_carts.html')
                context = {
                    'menu': for_cat_menu,
                    'request': request,
                    'path': request.path,
                    'user': request.user,
                    'session': request.session,
                    'carts': carts_on_page,
                    'p': p,
                    'cart_length': l,
                    'summ_in_cart': summ_in_cart(for_cart),
                    'status': Order.status_in_choices,
                    'form': form_,
                    'count': paginator.count,
                    'query_string': query_string,
                }
            return HttpResponse(template.render(context, request))
        #elif request.method == 'POST':
        #    form_ = DateTimeForm(request.POST)
        #    print(form_)
        #    if form_.is_valid():
        #        start_date = form_.cleaned_data['start_date']
        #        end_date = form_.cleaned_data['end_date']
        #        print(request.path + '?start_date=' + DateFormat(start_date).format('d/m/Y'))
        #        HttpResponseRedirect(reverse('adm_', kwargs={'startdate': DateFormat(start_date).format('d/m/Y')}))
        #    return HttpResponseRedirect(request.path)
        else:
            return HttpResponseRedirect(reverse_lazy('adm_'))
Example #24
0
def my_login(request, next_='/'):

    form_ = LoginForm()
    restore_form_ = RestoreForm()
    for_cat_menu = Category.objects.all()

    if ('next' in request.GET) and request.GET['next'].strip():
        next_ = request.GET['next']

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        # session = request.session['key']
        # print(request.session['last_date'], session)
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)

    else:
        return HttpResponseRedirect(reverse_lazy('index'))
    l = len(for_cart)
    isError = False
    if request.method == 'POST':
        if 'Login' in request.POST:
             form_ = LoginForm(request.POST)
             if form_.is_valid():
                user_ = form_.cleaned_data['login']
                password_ = form_.cleaned_data['password']
                user = authenticate(username=user_, password=password_)
                if user is not None:
                    add_to_cart(for_cart, user)
                    login(request, user)
                    # print(next_)
                    return HttpResponseRedirect(next_)
                else:
                    pass
                    # raise Http404()
        elif 'Restore' in request.POST:
            restore_form_ = RestoreForm(request.POST)
            if restore_form_.is_valid():
                username_ = restore_form_.cleaned_data['login']
                user = User.objects.filter(username=username_)
                # print(user)
                if user:
                    user = user[0]
                    email_ = user.email
                    new_key_ = Key.objects.create(login=user.username)
                    new_key_.save()
                    # print(new_key_)
                    to = [email_]
                    from_email = settings.DEFAULT_FROM_EMAIL
                    subject_ = 'Восстановление пароля'
                    text_content = render_to_string('bshop/email/restore.txt',
                                                    {'email': email_,
                                                     'username': username_,
                                                     'key': new_key_.key})
                    html_content = render_to_string('bshop/email/restore.html',
                                                    {'email': email_,
                                                     'username': username_,
                                                     'key': new_key_.key})
                    send_email(to, from_email, subject_, text_content, html_content)
                else:
                    isError = True
            else:
                isError = True
                # raise ValidationError('Пользователь с таким логином не зарегистрирован в системе', code='invalid')
                # print('Form is invalid or user not exist')

    template = loader.get_template('bshop/login.html')
    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session,
               'cart_length':l, 'summ_in_cart': summ_in_cart(for_cart), 'next': next_, 'form': form_, 'email_form': restore_form_, 'error': isError}
    return HttpResponse(template.render(context, request))
Example #25
0
def not_login(request, next_='/'):

    form_ = NotLoginForm()
    for_cat_menu = Category.objects.all()

    if ('next' in request.GET) and request.GET['next'].strip():
        next_ = request.GET['next']

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)

    else:
        return HttpResponseRedirect(reverse_lazy('cart'))
    l = len(for_cart)
    if request.method == 'POST':
         form_ = NotLoginForm(request.POST)
         if form_.is_valid():
            # print('Save order')
            p = form_.save_person()
            # print(p)
            owner_ = get_object_or_404(Client, user__username='******')
            cart_ = Cart.objects.filter(owner__user__username='******', key=request.session['key'], status=True)
            comment = form_.cleaned_data['comment']
            if not cart_:
                cart_ = Cart(owner=owner_, datetime=datetime.datetime.now(), key=request.session['key'])
                cart_.save()
            else:
                for item in cart_:
                    if item.status:
                        cart_ = item
                        break  # Пока берем первую запись не являющуюся заказом

            new_order = Order(list=cart_, datetime=datetime.datetime.now(), status='NEW', comment=comment, person=p)
            new_order.save()
            cart_.status = False
            cart_.summ = summ_in_cart(for_cart)
            cart_.save()
            # print(" Sending mail")
            for_order = CartElement.objects.filter(cart__id=new_order.list.id)
            # user = request.user
            to = [p.email]
            from_email = settings.DEFAULT_FROM_EMAIL
            subject_ = 'Новый заказ - ' + str(new_order.id)
            text_content = render_to_string('bshop/email/neworder.txt',
                                            {'first_name': p.first_name,
                                             'summ_in_cart': summ_in_cart(for_cart),
                                             'order': new_order,
                                             'positions': for_order})
            html_content = render_to_string('bshop/email/neworder.html',
                                            {'first_name': p.first_name,
                                             'summ_in_cart': summ_in_cart(for_cart),
                                             'order': new_order,
                                             'positions': for_order})
            # print(to, from_email, subject_, html_content)

            send_email(to, from_email, subject_, text_content, html_content)
            to = [settings.ADMIN_EMAIL]
            send_email(to, from_email, subject_, text_content, html_content)

            return HttpResponseRedirect(reverse_lazy('orders'))

    template = loader.get_template('bshop/notlogin.html')
    context = {'menu': for_cat_menu, 'path': request.path, 'user': request.user, 'session': request.session,
               'cart_length':l, 'summ_in_cart': summ_in_cart(for_cart), 'next': next_, 'form': form_}
    return HttpResponse(template.render(context, request))
Example #26
0
def my_login(request, next_='/'):

    form_ = LoginForm()
    restore_form_ = RestoreForm()
    for_cat_menu = Category.objects.all()

    if ('next' in request.GET) and request.GET['next'].strip():
        next_ = request.GET['next']

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        # session = request.session['key']
        # print(request.session['last_date'], session)
        for_cart = CartElement.objects.filter(cart__key=request.session['key'],
                                              cart__status=True)

    else:
        return HttpResponseRedirect(reverse_lazy('index'))
    l = len(for_cart)
    isError = False
    if request.method == 'POST':
        if 'Login' in request.POST:
            form_ = LoginForm(request.POST)
            if form_.is_valid():
                user_ = form_.cleaned_data['login']
                password_ = form_.cleaned_data['password']
                user = authenticate(username=user_, password=password_)
                if user is not None:
                    add_to_cart(for_cart, user)
                    login(request, user)
                    # print(next_)
                    return HttpResponseRedirect(next_)
                else:
                    pass
                    # raise Http404()
        elif 'Restore' in request.POST:
            restore_form_ = RestoreForm(request.POST)
            if restore_form_.is_valid():
                username_ = restore_form_.cleaned_data['login']
                user = User.objects.filter(username=username_)
                # print(user)
                if user:
                    user = user[0]
                    email_ = user.email
                    new_key_ = Key.objects.create(login=user.username)
                    new_key_.save()
                    # print(new_key_)
                    to = [email_]
                    from_email = settings.DEFAULT_FROM_EMAIL
                    subject_ = 'Восстановление пароля'
                    text_content = render_to_string(
                        'bshop/email/restore.txt', {
                            'email': email_,
                            'username': username_,
                            'key': new_key_.key
                        })
                    html_content = render_to_string(
                        'bshop/email/restore.html', {
                            'email': email_,
                            'username': username_,
                            'key': new_key_.key
                        })
                    send_email(to, from_email, subject_, text_content,
                               html_content)
                else:
                    isError = True
            else:
                isError = True
                # raise ValidationError('Пользователь с таким логином не зарегистрирован в системе', code='invalid')
                # print('Form is invalid or user not exist')

    template = loader.get_template('bshop/login.html')
    context = {
        'menu': for_cat_menu,
        'path': request.path,
        'user': request.user,
        'session': request.session,
        'cart_length': l,
        'summ_in_cart': summ_in_cart(for_cart),
        'next': next_,
        'form': form_,
        'email_form': restore_form_,
        'error': isError
    }
    return HttpResponse(template.render(context, request))
Example #27
0
def restorePwd(request):

    for_cat_menu = Category.objects.all()
    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'],
                                              cart__status=True)
    else:
        for_cart = CartElement.objects.filter(
            cart__owner__user__username=request.user.username,
            cart__status=True)
    if ('key' in request.GET) and request.GET['key'].strip():
        key_ = request.GET['key']
        # print("Get Change Password for key", key_)
    else:
        return HttpResponseRedirect(reverse_lazy('login'))

    l = len(for_cart)
    form_ = ChangePasswordForm()
    isChangeOk = False
    if request.method == 'POST':
        if key_:
            # print("POST Change Password for key", key_)
            form_ = ChangePasswordForm(request.POST)
            if form_.is_valid():
                # print('Edit ')
                try:
                    a = uuid.UUID(key_)
                    # print('Is valid uuid', a)
                    k = Key.objects.filter(key=key_)[0]
                    # print(k)
                    # k = get_object_or_404(Key, )
                    if k and not k.isUsed:
                        if timezone.now() < k.datetime + datetime.timedelta(
                                hours=24):
                            u = get_object_or_404(User, username=k.login)
                            # print(u, k)
                            try:
                                u.password = make_password(
                                    form_.cleaned_data.get('password'))
                                u.save()
                                k.isUsed = True
                                k.save()
                                isChangeOk = True
                                # return HttpResponseRedirect(reverse_lazy('login'))
                            except:
                                # print("Passsword change error")
                                form_.add_error(
                                    field=None,
                                    error=ValidationError(
                                        'Возникла ошибка при сохранении нового пароля, обратитесь к администратору',
                                        code='invalid'))
                        else:
                            # print("Key key is expired")
                            form_.add_error(
                                field=None,
                                error=ValidationError(
                                    'Срок действия ключа для восстановления пароля истек',
                                    code='invalid'))
                    else:
                        # print('key is used')
                        form_.add_error(
                            field=None,
                            error=ValidationError(
                                'Ключ для восстановления пароля уже использован',
                                code='invalid'))
                except:
                    # print('Is not valid uuid')
                    form_.add_error(
                        field=None,
                        error=ValidationError(
                            'Неверный формат ключа для восстановления пароля',
                            code='invalid'))

    template = loader.get_template('bshop/restore_password.html')
    context = {
        'menu': for_cat_menu,
        'path': request.path,
        'user': request.user,
        'session': request.session,
        'cart_length': l,
        'summ_in_cart': summ_in_cart(for_cart),
        'form': form_,
        'key': key_,
        'isChangeOk': isChangeOk
    }
    return HttpResponse(template.render(context, request))
Example #28
0
def not_login(request, next_='/'):

    form_ = NotLoginForm()
    for_cat_menu = Category.objects.all()

    if ('next' in request.GET) and request.GET['next'].strip():
        next_ = request.GET['next']

    if not request.user.is_authenticated():
        request.session.set_expiry(None)
        if 'key' not in request.session:
            request.session['last_date'] = str(datetime.datetime.now())
            request.session.save()
            request.session['key'] = request.session.session_key
        for_cart = CartElement.objects.filter(cart__key=request.session['key'],
                                              cart__status=True)

    else:
        return HttpResponseRedirect(reverse_lazy('cart'))
    l = len(for_cart)
    if request.method == 'POST':
        form_ = NotLoginForm(request.POST)
        if form_.is_valid():
            # print('Save order')
            p = form_.save_person()
            # print(p)
            owner_ = get_object_or_404(Client, user__username='******')
            cart_ = Cart.objects.filter(owner__user__username='******',
                                        key=request.session['key'],
                                        status=True)
            comment = form_.cleaned_data['comment']
            if not cart_:
                cart_ = Cart(owner=owner_,
                             datetime=datetime.datetime.now(),
                             key=request.session['key'])
                cart_.save()
            else:
                for item in cart_:
                    if item.status:
                        cart_ = item
                        break  # Пока берем первую запись не являющуюся заказом

            new_order = Order(list=cart_,
                              datetime=datetime.datetime.now(),
                              status='NEW',
                              comment=comment,
                              person=p)
            new_order.save()
            cart_.status = False
            cart_.summ = summ_in_cart(for_cart)
            cart_.save()
            # print(" Sending mail")
            for_order = CartElement.objects.filter(cart__id=new_order.list.id)
            # user = request.user
            to = [p.email]
            from_email = settings.DEFAULT_FROM_EMAIL
            subject_ = 'Новый заказ - ' + str(new_order.id)
            text_content = render_to_string(
                'bshop/email/neworder.txt', {
                    'first_name': p.first_name,
                    'summ_in_cart': summ_in_cart(for_cart),
                    'order': new_order,
                    'positions': for_order
                })
            html_content = render_to_string(
                'bshop/email/neworder.html', {
                    'first_name': p.first_name,
                    'summ_in_cart': summ_in_cart(for_cart),
                    'order': new_order,
                    'positions': for_order
                })
            # print(to, from_email, subject_, html_content)

            send_email(to, from_email, subject_, text_content, html_content)
            to = [settings.ADMIN_EMAIL]
            send_email(to, from_email, subject_, text_content, html_content)

            return HttpResponseRedirect(reverse_lazy('orders'))

    template = loader.get_template('bshop/notlogin.html')
    context = {
        'menu': for_cat_menu,
        'path': request.path,
        'user': request.user,
        'session': request.session,
        'cart_length': l,
        'summ_in_cart': summ_in_cart(for_cart),
        'next': next_,
        'form': form_
    }
    return HttpResponse(template.render(context, request))