Home > Software engineering >  Django Generate cookie before loading page
Django Generate cookie before loading page

Time:08-24

I'm building an e-commerce website and I'm generating device cookie to store unauthorized users' UUID. If user is not authorized it searches for their cookie and to display quantity of items in cart for given device (at navbar.html). When I run any page I get a KeyError: 'device' as it tries to call function that searches for a cookie which doesn't exist yet. Is there any workaround?

base.html

<html lang="en">
  <head>
    <script>

      function getCookie(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;
          }

      let device = getCookie('device');

      function uuidv4() {
        return ([1e7] -1e3 -4e3 -8e3 -1e11).replace(/[018]/g, c =>
          (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
        );
      }

      if (device == null || device == undefined) {
        device = uuidv4();
      }
      
      document.cookie = 'device='   device   ';domain=;path=/'
    </script>
  </head>
  {% include "navbar.html" %}
</html>

navbar.html

<span > {{ request|cart_item_count }} </span>

cart_tag.py

from django import template
from store.models import Order, Customer
register = template.Library()

@register.filter
def cart_item_count(request):
    try:
        customer = request.user.customer
    except AttributeError:
        device = request.COOKIES['device']
        customer, _ = Customer.objects.get_or_create(device=device)
    qs = Order.objects.filter(customer=customer, ordered=False)
    if qs.exists():
        return qs[0].items.count()
    return 0

EDIT: views.py

from django.views.generic import ListView
from .models import ShopItem
class HomeView(ListView):
    model = ShopItem
    paginate_by = 4
    template_name = "home-page.html"

models.py

from django.db import models
class ShopItem(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100)
    description = models.TextField()

CodePudding user response:

i think you should change your code like this maybe in cart_tag.py for initial None device cookie

from django import template
from store.models import Order, Customer

register = template.Library()


@register.filter
def cart_item_count(request):
    customer = None
    try:
        customer = request.user.customer
    except AttributeError:
        device = request.COOKIES.get('device', '')
        if device:
            customer, _ = Customer.objects.get_or_create(device=device)
    if customer:
        qs = Order.objects.filter(customer=customer, ordered=False)
        if qs.exists():
            return qs[0].items.count()
    return 0
  • Related