V
V
Vova1357982021-05-31 17:17:28
Django
Vova135798, 2021-05-31 17:17:28

How to add request to DetailView?

There is a piece of code that is responsible for displaying the number of items in the cart

data = cartData(request)
    cartItems = data['cartItems']
    order = data['order']
    items = data['items']

It somehow needs to be placed in the DetailView class so that the cart class Product_det(DetailView) also works on individual product pages. I tried, but nothing worked. Maybe it's better to put it in a separate tag?

view.py

view.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.http import JsonResponse
import json
import datetime
from .models import * 
from .utils import cookieCart, cartData, guestOrder

def store(request):
    data = cartData(request)

    cartItems = data['cartItems']
    order = data['order']
    items = data['items']

    products = Product.objects.all()
    context = {'products':products, 'cartItems':cartItems}
    return render(request, 'store/store.html', context)


class Product_det(DetailView):


    model = Product
    template_name = 'store/prod.html'
    context_object_name = 'product'

    def get_context_data(self, *args, **kwargs):
        cd = super().get_context_data(*args, **kwargs)

        # data = cartData(request)
        cartItems = data['cartItems']
        order = data['order']
        items = data['items']

        cd['data'] = data

        return cd



def cart(request):
    data = cartData(request)

    cartItems = data['cartItems']
    order = data['order']
    items = data['items']

    context = {'items':items, 'order':order, 'cartItems':cartItems}
    return render(request, 'store/cart.html', context)

def checkout(request):
    data = cartData(request)
    
    cartItems = data['cartItems']
    order = data['order']
    items = data['items']

    context = {'items':items, 'order':order, 'cartItems':cartItems}
    return render(request, 'store/checkout.html', context)

def updateItem(request):
    data = json.loads(request.body)
    productId = data['productId']
    action = data['action']
    print('Action:', action)
    print('Product:', productId)

    customer = request.user.customer
    product = Product.objects.get(id=productId)
    order, created = Order.objects.get_or_create(customer=customer, complete=False)

    orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)

    if action == 'add':
        orderItem.quantity = (orderItem.quantity + 1)
    elif action == 'remove':
        orderItem.quantity = (orderItem.quantity - 1)

    orderItem.save()

    if orderItem.quantity <= 0:
        orderItem.delete()

    return JsonResponse('Item was added', safe=False)

def processOrder(request):
    transaction_id = datetime.datetime.now().timestamp()
    data = json.loads(request.body)

    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
    else:
        customer, order = guestOrder(request, data)

    total = float(data['form']['total'])
    order.transaction_id = transaction_id

    if total == order.get_cart_total:
        order.complete = True
    order.save()

    if order.shipping == True:
        ShippingAddress.objects.create(
        customer=customer,
        order=order,
        address=data['shipping']['address'],
        city=data['shipping']['city'],
        state=data['shipping']['state'],
        zipcode=data['shipping']['zipcode'],
        )

    return JsonResponse('Payment submitted..', safe=False)


<!DOCTYPE html>
{% load static %}
<html>
<head>
    <title>Ecom</title>

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" />

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}">

    <script type="text/javascript">
        var user = '{{request.user}}'

        function getToken(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i].trim();
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        var csrftoken = getToken('csrftoken')

        function getCookie(name) {
            // Split cookie string and get all individual name=value pairs in an array
            var cookieArr = document.cookie.split(";");

            // Loop through the array elements
            for(var i = 0; i < cookieArr.length; i++) {
                var cookiePair = cookieArr[i].split("=");

                /* Removing whitespace at the beginning of the cookie name
                and compare it with the given string */
                if(name == cookiePair[0].trim()) {
                    // Decode the cookie value and return
                    return decodeURIComponent(cookiePair[1]);
                }
            }

            // Return null if not found
            return null;
        }
        var cart = JSON.parse(getCookie('cart'))

        if (cart == undefined){
            cart = {}
            console.log('Cart Created!', cart)
            document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
        }
        console.log('Cart:', cart)

    </script>

</head>
<body>

    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
      <a class="navbar-brand" href="{% url 'store' %}">Ecom</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <a class="nav-link" href="{% url 'store' %}">Store <span class="sr-only">(current)</span></a>
          </li>

        </ul>
        <div class="form-inline my-2 my-lg-0">
            <a href="#"class="btn btn-warning">Login</a>

            <a href="{% url 'cart' %}">
                <img  id="cart-icon" src="{% static 'images/cart.png' %}">
            </a>
            <p id="cart-total">{{data.Items}}</p>

        </div>
      </div>
    </nav>

     <div class="container">
            <br>
            <div class="row">

        <div class="col-lg-4">
            <img class="thumbnail" src="{{product.imageURL}}">
            <div class="box-element product">
                <h6><strong>{{product.name}}</strong></h6>
                <hr>

                <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>

                <a class="btn btn-outline-success" href="#">View</a>
                <h4 style="display: inline-block; float: right"><strong>${{product.price}}</strong></h4>

            </div>
        </div>

    </div>
         </div>


    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

    <script type="text/javascript" src="{% static 'js/cart.js' %}"></script>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-06-02
@Vova135798

data = cartData(self.request)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question