Ejemplo n.º 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
                  })
Ejemplo n.º 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")
Ejemplo n.º 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)
Ejemplo n.º 4
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()
Ejemplo n.º 5
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', '/'))
Ejemplo n.º 6
0
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
    })
Ejemplo n.º 7
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)
Ejemplo n.º 8
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)
Ejemplo n.º 9
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
    })
Ejemplo n.º 10
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'))
Ejemplo n.º 11
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})
Ejemplo n.º 12
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')
Ejemplo n.º 13
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()
Ejemplo n.º 14
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
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
 def get_cart(self):
     if self.request.user.is_authenticated:
         user_id = self.request.user.id
         try:
             cart = Cart.objects.get(user_id=user_id)
         except ObjectDoesNotExist:
             cart = Cart(user_id=user_id,
                         total_cost=0)
             cart.save()
     else:
         session_key = self.request.session.session_key
         if not session_key:
             self.request.session.save()
             session_key = self.request.session.session_key
         try:
             cart = Cart.objects.get(session_key=session_key)
         except ObjectDoesNotExist:
             cart = Cart(session_key=session_key,
                         total_cost=0)
             cart.save()
     return cart
Ejemplo n.º 17
0
def cart():
    cart = Cart.query.filter_by(ordered=False, user_id=current_user.id).first()
    if request.method == 'POST':
        if not cart:
            cart = Cart(user_id=current_user.id, ordered=False)
        db.session.add(cart)
        db.session.commit()
        product_id = request.form.get('product_id')
        statement = association_table.insert().values(
            cart_id=cart.id, product_id=int(product_id))
        db.session.execute(statement)
        db.session.commit()
    return render_template('cart.html', cart=cart)
Ejemplo n.º 18
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")   # 로그인 페이지로 이동
Ejemplo n.º 19
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
Ejemplo n.º 20
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)
Ejemplo n.º 21
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = load_user(form.username.data)
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=True)
        Cart(True)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    return render_template('shop/login.html', title='Sign In', form=form)
Ejemplo n.º 22
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')
Ejemplo n.º 23
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)
Ejemplo n.º 24
0
def add_cart_to_database(user, size, tshirt):
    size = SizeVariant.objects.get(size=size, tshirt=tshirt)
    existing = Cart.objects.filter(user=user, sizeVariant=size)

    if len(existing) > 0:
        obj = existing[0]
        obj.quantity = obj.quantity + 1
        obj.save()

    else:
        c = Cart()
        c.user = user
        c.sizeVariant = size
        c.quantity = 1
        c.save()
Ejemplo n.º 25
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
Ejemplo n.º 26
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)
Ejemplo n.º 27
0
    def post(self , request):
        add = request.session.get('plusItem')
        form = CustomerAuthForm(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user:
                loginuser(request, user)

                session_cart = request.session.get('cart')
                if session_cart is None:
                    session_cart = []
                else:
                    for c in session_cart:
                        size = c.get('size')
                        tshirt_id = c.get('tshirt')
            
                        quantity = c.get('quantity')+1
                        cart_obj = Cart()
                        cart_obj.sizeVariant = SizeVariant.objects.get(
                            size=size, tshirt=tshirt_id)
                        cart_obj.quantity = quantity
                        cart_obj.user = user
                        cart_obj.save()

                # { size , tshirt , quantiti }
                cart = Cart.objects.filter(user=user)
                session_cart = []
                for c in cart:
                    obj = {
                        'size': c.sizeVariant.size,
                        'tshirt': c.sizeVariant.tshirt.id,
                        'quantity': c.quantity
                    }
                    session_cart.append(obj)

                request.session['cart'] = session_cart
                next_page = request.session.get('next_page')
                if next_page is None:
                    next_page = 'homepage'
                return redirect(next_page)
        else:
            return render(request,
                          template_name='login.html',
                          context={'form': form})
Ejemplo n.º 28
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")   # 로그인 페이지로 이동
Ejemplo n.º 29
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)
Ejemplo n.º 30
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,
                  })