Exemple #1
0
def show_product(request, slug):
    template = 'shop/product.html'
    all_category = Category.objects.all()
    all_subcategory = SubCategory.objects.all()
    all_entries = Product.objects.filter(slug=slug)
    for each in all_entries:
        model_product = each.id
    all_reviews = Review.objects.filter(product=model_product)
    if request.method == 'POST' and request.user.is_authenticated:
        product = get_object_or_404(Product, slug=slug)
        acc = User.objects.get(email=request.user.email)
        if Cart.objects.all().filter(user=acc, product=product).exists():
            cart = Cart.objects.get(user=acc, product=product)
            Cart.objects.all().filter(
                user=acc, product=product).update(pr_count=cart.pr_count + 1)
        else:
            new_cart = Cart(user=acc, product=product, pr_count=1)
            new_cart.save()
    return render(request,
                  template,
                  context={
                      'product': all_entries,
                      'reviews': all_reviews,
                      'categorys': all_category,
                      'subcategorys': all_subcategory
                  })
Exemple #2
0
def add_to_cart(request):
    userID = request.user.id
    itemID = int(request.POST.get('itemID', 0))
    quantity = int(request.POST.get('qnty', 0))
    request.session['view'] = 'shop'
    try:
        item = Shop.objects.get(id=itemID)
    except:
        item = None

    cart = []
    try:
        #if len(Cart.objects.all()) > 0:
        cart = Cart.objects.get(item_id=itemID)
    except Cart.DoesNotExist:
        cart = None
    if not cart:
        cart = Cart(user_id=userID,
                    item_id=itemID,
                    qnty=quantity,
                    total_price=item.price)
    else:
        cart.qnty = cart.qnty + quantity
    cart.save()
    response_data = {}

    try:
        response_data['result'] = 'Ok'
    except:
        response_data['result'] = 'not ok'
    return HttpResponse(json.dumps(response_data),
                        content_type="application/json")
Exemple #3
0
 def post(self, request):
     if request.POST.get('email'):
         name = request.POST.get('name')
         phone = request.POST.get('phone')
         email = request.POST.get('email')
         customer = Customer(name=name, phone=phone, email=email)
         customer.save()
         qrcode_path = customer.qrcode_create()
         customer.qrcode = qrcode_path
         customer.save()
         order = Order(customer=customer, )
         order.save()
         cart = request.session.get('cart')
         if cart:
             for product_id, quantity in cart.items():
                 cart = Cart(product_id=product_id,
                             quantity=quantity,
                             order=order,
                             complete=True)
                 cart.save()
             del request.session['cart']
             request.session.save()
     cart = order.cart_set.all()
     context = {'cart': cart, 'order': order}
     return render(request, 'shop/order.html', context)
Exemple #4
0
def add_to_cart(request, pk):
    # Get current user and product
    current_user = request.user
    product = Product.objects.get(pk=pk)

    # Look if user has existing cart
    cart_count = Cart.objects.filter(user=current_user).count()
    if cart_count is 0:
        # Create new cart
        cart = Cart(user=current_user)
        cart.save()
    else:
        # Use existing cart for user
        cart = Cart.objects.get(user=current_user)

    # Create snapshot and add to user basket
    article, created = CartItem.objects.get_or_create(product=product,
                                                      user_cart=cart)
    article.price_snapshot = product.price
    if request.POST.get("quantity").isdigit():
        article.quantity = request.POST.get("quantity", "1")
    else:
        article.quantity = 1
    article.save()

    messages.info(request, "{} has been added to cart.".format(product.name))

    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
Exemple #5
0
def add_to_cart(request):
    user = request.user
    itemID = int(request.POST.get('itemID', 0))
    quantity = int(request.POST.get('qnty', 0))
    request.session['view'] = 'shop';

    try:
        item = Shop.objects.get(id=itemID)
    except:
        item = None

    cart = []
    try:
    #if len(Cart.objects.all()) > 0:
        cart = Cart.objects.get(item_id=itemID,user_id=user)
        cart.qnty=cart.qnty+quantity
    except Cart.DoesNotExist:
        cart = None
        cart = Cart(user_id=user, item_id=item, qnty=quantity)


    cart.save()
    response_data = {}


    try:
        response_data['result'] = 'Ok'
    except:
        response_data['result'] = 'not ok'
    return HttpResponse(json.dumps(response_data), content_type="application/json")
def register_user(request):
    user = request.user
    if not user.is_anonymous:
        return redirect('login:home')
    warning = ""
    Userform = RegisterForm(request.POST or None)
    if request.method == "POST":
        if Userform.is_valid(
        ):  #i am using Javascript to check for confirm password and password matching
            try:
                User.objects.get(email__iexact=form.cleaned_data['email'])
                warning = "User with following email exists"
            except Exception as e:
                ob = Userform.save()
                cart = Cart()
                cart.user = ob
                cart.save()
                otp = Otp()
                otp.user = ob
                otp.save()
                log_in(request, ob)
                return redirect('login:verify_user')
    return render(request, "login/register.html", {
        'form1': Userform,
        'warning': warning
    })
Exemple #7
0
def get_common_context(request):
    c = {}
    c['request_url'] = request.path
    c['user'] = request.user
    c['authentication_form'] = AuthenticationForm()
    c['categories'] = Category.objects.filter(parent=None).extra(order_by = ['id'])
    c['brands'] = Brand.objects.all()
    c['colors'] = Color.objects.all()
    c['materials'] = Material.objects.all()
    c['news_left'] = NewsItem.objects.all()[0:3]
    c['user_opt'] = request.user.is_authenticated() and request.user.get_profile().is_opt 
    
    if request.user.is_authenticated():
        c['cart_working'] = Cart
        Cart.update(request.user, SessionCartWorking(request).pop_content())
    else:
        c['cart_working'] = SessionCartWorking(request)
    c['cart_count'], c['cart_sum'] = c['cart_working'].get_goods_count_and_sum(request.user)
    c['cart_content'] = c['cart_working'].get_content(request.user)
    c.update(csrf(request))
    
    if request.method == 'POST' and 'action' in request.POST and request.POST['action'] == 'call_request':
        from call_request.forms import CallRequestForm
        crf = CallRequestForm(request.POST)
        if crf.is_valid():
            crf.save()
            c['call_sent'] = True
        else:
            c['crf'] = crf
    
    return c
Exemple #8
0
def addtocart_prodpage(request):
    token = request.session.get("token")
    dict = {}
    try:
        user = User.objects.get(token = token)
        prod_id = request.GET.get("prod_id")
        product = Product.objects.get(prod_id=prod_id)

        prod_num = int(request.GET.get("prod_num"))
        # print(prod_num)
        cart = Cart.objects.get(user=user,product=product,is_delete=False)
        try:

            cart.prod_num = cart.prod_num + prod_num
            if cart.prod_num <= product.prod_num :
                cart.save()
            else:
                raise Exception
            dict["status"] = "success"
        except Exception as e:
            print(e)
            dict["status"] = "error"
    except User.DoesNotExist :
        dict["status"] = "nologin"
    except Cart.MultipleObjectsReturned as e:
        dict["status"] = "error"
    except Cart.DoesNotExist as e:
        if prod_num<=product.prod_num:
            cart = Cart(user=user, product=product, prod_num=prod_num)
            cart.save()
            dict["status"] = "success"
        else:
            dict["status"] = "error"

    return JsonResponse(dict)
Exemple #9
0
def category_view(request, category_slug):
    '''Single category pages'''
    category = Category.objects.get(slug=category_slug)
    product_of_category = Product.objects.filter(category=category)
    products = Product.objects.all()
    categories = Category.objects.filter(priority=True)
    categories_all = Category.objects.all()
    category_title = Category.objects.get(slug=category_slug)
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.objects.get(id=cart_id)
    context = {
        'product_of_category': product_of_category,
        'categories_all': categories_all,
        'categories': categories,
        'products': products,
        'cart': cart,
        'category_title': category_title,
    }
    context = {**context, **context_1}
    return render(request, 'category.html', context=context)
Exemple #10
0
def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save()
            order.user = request.user
            order.save()
            for item in cart:
                OrderItem.objects.create(order=order,
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
            # очистка корзины
            cart.clear()
            # запуск асинхронной задачи
            order_created.delay(order.id)
            # set the order in the session
            request.session['order_id'] = order.id
            # redirect to the payment
        return redirect(reverse('payment:process'))
    else:
        form = OrderCreateForm
    return render(request, 'orders/order/create.html', {
        'cart': cart,
        'form': form
    })
Exemple #11
0
def cart_add(cate_id, product_id):
    form = CartAddProductForm()
    cart = Cart()
    product = load_product(product_id)
    if form.validate_on_submit():
        cart.add(product=product,
                 num=form.num.data,
                 update_num=form.update.data)
    return redirect(url_for('cart_detail'))
Exemple #12
0
def addtocart(request,id):
	r=Product.objects.get(id=id)
	if request.method == 'POST':
		p=Cart(user_id=request.user.id,product_id=id)
		p.save()
		
		return redirect('main')
	
	return render(request,'shop/tb.html',{'data':r})
Exemple #13
0
def check_cart(request):
    cart_id = request.session.get('cart_id')
    if cart_id is not None:
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.item.count()
    else:
        cart = Cart()
        cart.save()
        request.session['cart_id'] = cart.id
    return cart
Exemple #14
0
def cart_insert(request):
    # 세션변수 userid 확인, 없으면 빈문자열이 리턴됨
    uid = request.session.get("userid", "")
    if uid != "": # 로그인한 상태
        vo = Cart(userid = uid,
                    product_id = request.POST["product_id"],
                    amount = request.POST["amount"])

        vo.save() # 장바구니 테이블에 추가
        return redirect("/cart_list")   # 장바구니 목록으로 이동

    else: # 로그인하지 않은 상태
        return redirect("/login")   # 로그인 페이지로 이동
Exemple #15
0
def get_logged_user_cart(user):
    """
        Get active cart of the user
        If he don't have one then a new cart is created.
    """
    carts = Cart.objects.filter(user__id=user.id, active=True)
    if len(carts) == 0:
        cart = Cart(user=user, active=True)
        cart.save()
    else:
        cart = carts[0]

    return cart
Exemple #16
0
def order_create():
    form = OrderCreateForm()
    if form.validate_on_submit():
        cart = Cart()
        if len(cart) == 0:
            return redirect(url_for('index'))
        order = Order(form.name.data, form.phone.data, form.address.data)
        order.create(cart)
        cart.clear()
        return render_template('shop/cart/created.html',
                               form=form,
                               order=order)
    return render_template('shop/cart/create.html', form=form)
Exemple #17
0
def Add_To_Cart(request, id):
    product = Product.objects.all()
    item = Product.objects.get(pk=id)
    print(item)
    if not (Cart.objects.filter(product_id=item.id).exists()):
        cart = Cart(product_id=item.id)
    else:
        cart = Cart.objects.get(product_id=item.id)
        cart.amount += 1

    cart.save()
    #print(cart)

    return redirect(to='index')
Exemple #18
0
def make_order_view(request):
    '''Page order'''
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.objects.get(id=cart_id)
    form = OrderForm(request.POST or None)
    images = ThemeFront.objects.all()
    categories = Category.objects.filter(priority=True)
    context = {
        'cart': cart,
        'images': images,
        'categories': categories,
    }
    context = {**context, **context_1}
    if form.is_valid():
        name = form.cleaned_data['name']
        last_name = form.cleaned_data['last_name']
        phone = form.cleaned_data['phone']
        buying_type = form.cleaned_data['buying_type']
        sail = form.cleaned_data['sail']
        date_delivery = form.cleaned_data['date_delivery']
        address_true = form.cleaned_data['address_true']
        comment = form.cleaned_data['comment']

        new_order = Order()
        new_order.user = request.user
        new_order.save()
        new_order.items.add(cart)
        new_order.first_name = name
        new_order.last_name = last_name
        new_order.phone = phone
        new_order.buying_type = buying_type
        new_order.sail = sail
        new_order.date_delivery = date_delivery
        new_order.address = address_true
        new_order.comment = comment
        new_order.total = cart.cart_total
        new_order.save()
        del request.session['cart_id']
        del request.session['total']
        return HttpResponseRedirect(reverse('thank_you'))
    return render(request, 'thank_you.html', context=context)
Exemple #19
0
def get_common_context(request):
    c = context()
    c["request_url"] = request.path
    c["user"] = request.user
    c["authentication_form"] = AuthenticationForm()
    c["car_models"] = CarModel.objects.all()
    c["colors"] = Color.objects.all()
    c["categories"] = Category.objects.all()
    if request.user.is_authenticated():
        c["cart_working"] = Cart
        Cart.update(request.user, SessionCartWorking(request).pop_content())
    else:
        c["cart_working"] = SessionCartWorking(request)
    c["cart_count"], c["cart_sum"] = c["cart_working"].get_goods_count_and_sum(request.user)
    c.update(csrf(request))
    return c
Exemple #20
0
    def process_request(self, request):
        """
        Fetch cart from database by session id. If it doesn't exist, create a new cart instance
        but do not save it (Yet). We will save it in as soon as an item is added to it.
        """

        try:
            cart = Cart.objects.get(session_id=request.session.session_key)

        except Cart.DoesNotExist:
            cart = Cart()
            cart.session_id = request.session.session_key
            request.session.modified = True
            request.session.save()

        request.cart = cart
Exemple #21
0
    def process_request(self, request):
        """
        Fetch cart from database by session id. If it doesn't exist, create a new cart instance
        but do not save it (Yet). We will save it in as soon as an item is added to it.
        """

        try:
            cart = Cart.objects.get(session_id=request.session.session_key)

        except Cart.DoesNotExist:
            cart = Cart()
            cart.session_id = request.session.session_key
            request.session.modified = True
            request.session.save()

        request.cart = cart
Exemple #22
0
def cart_update(request):
    uid = request.session.get("userid", "") # 세션변수
    if uid != "":   # 세션값이 있으면(로그인한 상태)
        # 폼 데이터가 배열값인 경우 getlist("배열이름")
        amt = request.POST.getlist("amount")
        cid = request.POST.getlist("cart_id")
        pid = request.POST.getlist("product_id")
        for idx in range(len(cid)):
            vo = Cart(cart_id = cid[idx],
                        userid = uid,
                        product_id = pid[idx],
                        amount = amt[idx])
        vo.save()   # 저장
        return redirect("/cart_list")   # 장바구니 목록으로 이동

    else:   # 세션이 없으면(로그인하지 않은 경우)
        return redirect("/login")   # 로그인 페이지로 이동
Exemple #23
0
def product_view(request, product_slug):
    try:
        cart_id = request.session['cart_id']
        cart = Cart.object.get(id=cart_id)
        request.session['total'] = CartItem.object.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.object.get(id=cart_id)
    product = Product.object.get(slug=product_slug)
    context = {
        'product': product,
        'cart': cart,
    }
    return render(request, 'product.html', context)
Exemple #24
0
def checkout_view(request):
    try:
        cart_id = request.session['cart_id']
        cart = Cart.object.get(id=cart_id)
        request.session['total'] = CartItem.object.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.object.get(id=cart_id)
    new_cart_total = 0.00
    for item in cart.items.all():
        new_cart_total += float(item.item_total)
    cart.cart_total = new_cart_total
    cart.save
    form = OrderForms(request.POST or None)
    if form.is_valid():
        first_name = form.cleaned_data['name']
        last_name = form.cleaned_data['last_name']
        phone = form.cleaned_data['phone']
        buying_type = form.cleaned_data['buying_type']
        address = form.cleaned_data['address']
        comments = form.cleaned_data['comments']
        print(buying_type)
        new_order = Order.object.create(
            user = request.user,
            items = cart,
            total = cart.cart_total,
            first_name = first_name,
            last_name = last_name,
            phone = phone,
            address = address,
            buying_type = buying_type,
            comments = comments,
        )
        del request.session['cart_id']
        del request.session['total']
        return HttpResponseRedirect(reverse('thanks'))
    context = {
        'cart': cart,
        'cart_total':CartItem.object.count(),
        'form': form
    }
    return render(request, 'checkout.html', context)
Exemple #25
0
def get_common_context(request):
    c = {}
    c['request_url'] = request.path
    c['user'] = request.user
    c['categories'] = Category.objects.filter(parent=None).extra(order_by = ['id'])
    c['news_left'] = NewsItem.objects.all()[0:3] 
    
    if request.user.is_authenticated():
        c['cart_working'] = Cart
        Cart.update(request.user, SessionCartWorking(request).pop_content())
    else:
        c['cart_working'] = SessionCartWorking(request)
    c['cart_count'], c['cart_sum'] = c['cart_working'].get_goods_count_and_sum(request.user)
    c['cart_content'] = c['cart_working'].get_content(request.user)
    c['slideshow'] = Slider.objects.all()
    c.update(csrf(request))
    
    return c
Exemple #26
0
def products(request, slug):
    template = 'shop/products_new.html'
    all_category = Category.objects.all()
    all_subcategory = SubCategory.objects.all()
    click_subcategory = SubCategory.objects.filter(slug=slug)
    for each in click_subcategory:
        product_name = each.id
        current_subcategory = each.name
    click_product = Product.objects.filter(subcategory=product_name)
    paginator = Paginator(Product.objects.all(), 2)
    current_page = request.GET.get('page', 1)
    articles = paginator.get_page(current_page)
    prev_page_number = next_page_number = 0
    if articles.has_previous():
        prev_page_number = int(current_page) - 1
    if articles.has_next():
        next_page_number = int(current_page) + 1
    prev_page_url = urllib.parse.urlencode({'page': prev_page_number})
    next_page_url = urllib.parse.urlencode({'page': next_page_number})
    prev_page_url = slug + '?' + str(prev_page_url)
    next_page_url = slug + '?' + str(next_page_url)
    if request.method == 'POST' and request.user.is_authenticated:
        product = get_object_or_404(Product, slug=slug)
        acc = User.objects.get(email=request.user.email)
        if Cart.objects.all().filter(user=acc, product=product).exists():
            cart = Cart.objects.get(user=acc, product=product)
            Cart.objects.all().filter(
                user=acc, product=product).update(pr_count=cart.pr_count + 1)
        else:
            new_cart = Cart(user=acc, product=product, pr_count=1)
            new_cart.save()

    return render(request,
                  template,
                  context={
                      'products': click_product,
                      'categorys': all_category,
                      'subcategorys': all_subcategory,
                      'current': current_subcategory,
                      'current_page': current_page,
                      'prev_page_url': prev_page_url,
                      'next_page_url': next_page_url,
                  })
def add_product(update: Update, context: CallbackContext):
    query = update.callback_query
    query.answer()
    chat_id = query.from_user.id
    username = query.from_user.username
    product_callback_raw = update.callback_query.message.caption
    product_callback_split = product_callback_raw.split("\n")
    p = Product.objects.filter(
        name=product_callback_split[0]).values_list("pk")
    product_callback_id = str(p[0]).replace('(',
                                            '').replace(')',
                                                        '').replace(',', '')
    c, created = Customer.objects.get_or_create(telegram_id=chat_id,
                                                defaults={
                                                    'name':
                                                    query.from_user.username,
                                                })
    user = Customer.objects.filter(name=username).values_list("pk")
    user_ = str(user[0]).replace('(', '').replace(')', '').replace(',', '')
    cart_ = Cart.objects.filter(
        customer_id=user_,
        product_id=product_callback_id).values_list("quantity")
    if cart_:
        quantity_ = Cart.objects.filter(
            customer_id=user_,
            product_id=product_callback_id).values_list("quantity")
        new_quantity = str(quantity_[0]).replace('(', '').replace(')',
                                                                  '').replace(
                                                                      ',', '')
        update_cart = int(new_quantity) + 1
        c = Cart.objects.get(customer_id=user_, product_id=product_callback_id)
        c.quantity = update_cart
        c.save()
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=f" +1 {product_callback_split[0]}\n")
    else:
        c = Cart(customer_id=user_, product_id=product_callback_id, quantity=1)
        c.save()
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=
            f"<b>{username}</b> {product_callback_split[0]} added to your cart",
            parse_mode=telegram.ParseMode.HTML)
Exemple #28
0
def base_view(request):
    try:
        cart_id = request.session['cart_id']
        cart = Cart.object.get(id=cart_id)
        request.session['total'] = CartItem.object.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.object.get(id=cart_id)
    categories = Category.object.all()
    products = Product.object.all()
    context = {
        'categories': categories,
        'products': products,
        'cart': cart,
    }
    return render(request, 'main.html', context)
Exemple #29
0
def checkout_view(request):
    '''Page pre order'''
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.objects.get(id=cart_id)
    categories = Category.objects.filter(priority=True)
    context = {
        'cart': cart,
        'categories': categories,
    }
    context = {**context, **context_1}
    return render(request, 'checkout.html', context=context)
Exemple #30
0
def buynow(request, prid):
    current_user = request.user
    Cart.objects.filter(user_id=current_user.id).delete()
    data = Cart()
    data.user_id = current_user.id
    data.product_id = prid
    data.qty = 1
    data.save()
    return HttpResponseRedirect('/cart')
Exemple #31
0
def add_product_to_cart(user, product=None, count=1):
    for item in range(0, count):
        cart = Cart()
        if product is not None:
            cart.product = product
        else:
            cart.product = add_random_product()
        cart.created_by = user
        cart.save()
Exemple #32
0
def cart(item_id=0):
    if not item_id == 0:
        new_item = Cart.query.filter_by(item_id=item_id).first()
        if not new_item:
            new_item = Cart(item_id=item_id)
            db.session.add(new_item)
            db.session.commit()
    items = Cart.query.all()
    records = []
    for item in items:
        records.append(db.session.query(Record).get(item.item_id))
    return render_template('cart.html', title='Cart', records=records)
Exemple #33
0
def order_create_view(request):
    '''Registration order'''
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.objects.get(id=cart_id)
    form = OrderForm(request.POST or None)
    categories = Category.objects.filter(priority=True)
    context = {
        'form': form,
        'cart': cart,
        'categories': categories,
    }
    context = {**context, **context_1}
    return render(request, 'order.html', context=context)
Exemple #34
0
def home_view(request):
    template = 'shop/index.html'
    all_products = Product.objects.all()
    all_category = Category.objects.all()
    all_subcategory = SubCategory.objects.all()
    all_articles = Article.objects.all().order_by('-id')
    paginator = Paginator(Product.objects.all(), 3)
    current_page = request.GET.get('page', 1)
    things = paginator.get_page(current_page)
    prev_page_number = next_page_number = 0
    if things.has_previous():
        prev_page_number = int(current_page) - 1
    if things.has_next():
        next_page_number = int(current_page) + 1
    prev_page_url = urllib.parse.urlencode({'page': prev_page_number})
    next_page_url = urllib.parse.urlencode({'page': next_page_number})
    prev_page_url = str(prev_page_url)
    next_page_url = str(next_page_url)
    if request.method == 'POST' and request.user.is_authenticated:
        product = get_object_or_404(Product)
        acc = User.objects.get(email=request.user.email)
        if Cart.objects.all().filter(user=acc, product=product).exists():
            cart = Cart.objects.get(user=acc, product=product)
            Cart.objects.all().filter(
                user=acc, product=product).update(pr_count=cart.pr_count + 1)
        else:
            new_cart = Cart(user=acc, product=product, pr_count=1)
            new_cart.save()
    return render(request,
                  template,
                  context={
                      'products': things,
                      'all_products': all_products,
                      'categorys': all_category,
                      'articles': all_articles,
                      'subcategorys': all_subcategory,
                      'current_page': current_page,
                      'prev_page_url': prev_page_url,
                      'next_page_url': next_page_url
                  })
Exemple #35
0
def add_to_cart(for_cart, user):
    ''' Добавляет позиции корзины неавторизованного пользователя к корзине авторизованного.
    Вызывается при входе пользователя, либо его регистрации

    '''
    for position in for_cart:
        owner_ = get_object_or_404(Client, user__username=user.username)
        # quantity_ = int(form.cleaned_data['quantity'])
        product_ = get_object_or_404(Product, id=position.product.id)
        # cartElement_ = CartElement.objects.create(product=product_, quantity=quantity_, is_preorder=False)
        cart_ = Cart.objects.filter(owner__user__username=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_:
            cartElement_ = position
            cart_.cartElement.add(cartElement_)
            cart_.save()
        else:
            # Ориентируемся что пока у пользователя только одна текущая корзина
            cartElement_[
                0].quantity = cartElement_[0].quantity + position.quantity
            cartElement_[0].save()
Exemple #36
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))