I want my system to remember not only the products of logged in people, but also those who are not logged in. I made about the same cookie system for cart and wishlist that works until you loogged out. I’ll put everything because idk where exactly to look
main.html script part
<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();
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) {
var cookieArr = document.cookie.split(";");
for(var i = 0; i < cookieArr.length; i++) {
var cookiePair = cookieArr[i].split("=");
if(name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
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)
var wishlist = JSON.parse(getCookie('wishlist'))
if (wishlist == undefined){
wishlist = {}
console.log('wishlist Created!', wishlist)
document.cookie ='wishlist=' + JSON.stringify(wishlist) + ";domain=;path=/"
}
console.log('Wishlist:', wishlist)
cart.html (wishlist almost the same)
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-lg-12">
<div class="box-element">
<a class="btn btn-outline-dark" href="{% url 'store' %}">← Continue Shopping</a>
<br>
<br>
<table class="table">
<tr>
<th><h5>Items: <strong>{{order.get_cart_items}}</strong></h5></th>
<th><h5>Total:<strong> {{order.get_cart_total|floatformat:0}}₽</strong></h5></th>
<th>
<a style="float:right; margin:5px;" class="btn btn-dark" href="{% url 'checkout' %}">Checkout</a>
</th>
</tr>
</table>
</div>
<br>
<div class="box-element">
<div class="cart-row">
<div style="flex:2"></div>
<div style="flex:2"><strong>Item</strong></div>
<div style="flex:1"><strong>Color</strong></div>
<div style="flex:1"><strong>Size</strong></div>
<div style="flex:1"><strong>Sex</strong></div>
<div style="flex:1"><strong>Price</strong></div>
<div style="flex:1"><strong>Quantity</strong></div>
<div style="flex:1"><strong>Total</strong></div>
</div>
{% for item in items %}
<div class="cart-row">
<div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div>
<div style="flex:2"><p>{{item.product.name}}</p></div>
<div style="flex:1"><p>{{item.product.color}}</p></div>
<div style="flex:1"><p>{{item.product.size}}</p></div>
<div style="flex:1"><p>{{item.product.sex}}</p></div>
<div style="flex:1"><p>{{item.product.price|floatformat:0}}₽</p></div>
<div style="flex:1">
<p class="quantity">{{item.quantity}}</p>
<div class="quantity">
<img data-product="{{item.product.id}}" data-action="add" class="chg-quantity update-cart" src="{% static 'images/arrow-up.png' %}">
<img data-product="{{item.product.id}}" data-action="remove" class="chg-quantity update-cart" src="{% static 'images/down-arrow.png' %}">
</div>
</div>
<div style="flex:1"><p>{{item.get_total|floatformat:0}}₽</p></div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock content %}
cart.js
var updateBtns = document.getElementsByClassName('update-cart')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId, 'Action:', action)
console.log('USER:', user)
if (user == 'AnonymousUser'){
addCookieItem(productId, action)
}else{
updateUserOrder(productId, action)
}
})
}
function updateUserOrder(productId, action){
console.log('User is authenticated, sending data...')
var url = '/update_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'productId':productId, 'action':action})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
function addCookieItem(productId, action){
console.log('User is not authenticated')
if (action == 'add'){
if (cart[productId] == undefined){
cart[productId] = {'quantity':1}
}else{
cart[productId]['quantity'] += 1
}
}
if (action == 'remove'){
cart[productId]['quantity'] -= 1
if (cart[productId]['quantity'] <= 0){
console.log('Item should be deleted')
delete cart[productId];
}
}
console.log('CART:', cart)
document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
location.reload()
}
wishlist.js (almost the same)
var updateBtns = document.getElementsByClassName('update-wishlist')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId, 'Action:', action)
console.log('USER:', user)
if (user == 'AnonymousUser'){
addCookieItem(productId, action)
}else{
updateUserWish(productId, action)
}
})
}
function updateUserWish(productId, action){
console.log('User is authenticated, sending data...')
var url = '/update_wish_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'productId':productId, 'action':action})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
function addCookieItem(productId, action){
console.log('User is not authenticated')
if (action == 'add'){
if (wishlist[productId] == undefined){
wishlist[productId] = {'quantity':1}
}else{
if wishlist[productId]['quantity'] == 1:
wishlist[productId]['quantity'] += 0
}
}
if (action == 'remove'){
wishlist[productId]['quantity'] -= 1
if (wishlist[productId]['quantity'] <= 0){
console.log('Item should be deleted')
delete wishlist[productId];
}
}
console.log('WISHLIST:', wishlist)
document.cookie ='wishlist=' + JSON.stringify(wishlist) + ";domain=;path=/"
location.reload()
}
models.py for orders and wishes:
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
def __str__(self):
return str(self.id)
@property
def shipping(self):
shipping = False
orderitems = self.orderitem_set.all()
for i in orderitems:
if i.product.status == True:
shipping = True
return shipping
@property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
@property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
class Wish(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_wished = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
def __str__(self):
return str(self.id)
@property
def get_wish_items(self):
wishitems = self.wishitem_set.all()
total = sum([witem.quantity for witem in wishitems])
return total
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
@property
def get_total(self):
total = self.product.price * self.quantity
return total
class WishItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
wish = models.ForeignKey(Wish, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
urls.py
from django.contrib.auth.views import PasswordChangeView
from . import views
from .forms import PasswordUpdateForm
urlpatterns = [
path('', views.store, name="store"),
path('cart/', views.cart, name="cart"),
path('checkout/', views.checkout, name="checkout"),
path('login/', views.loginPage, name="login"),
path('logout/', views.logoutUser, name="logout"),
path('registration/', views.registrationPage, name="registration"),
path('profile/', views.profile, name="profile"),
path('change_password/', PasswordChangeView.as_view(template_name='store/change_password.html', success_url='profile', form_class=PasswordUpdateForm ), name="change_password"),
path('change_password/profile/', views.profile, name="profile"),
path('filter_products/', views.filter_products, name="filter_products"),
path('update_item/', views.updateItem, name="update_item"),
path('update_wish_item/', views.updateWishItem, name="update_wish_item"),
path('process_order/', views.processOrder, name="process_order"),
path('wishlist/', views.wishlist, name="wishlist"),
path('search/', views.search, name="search"),
path('<int:id>', views.product_view, name="product_view"),
path('search/<int:id>',views.product_view, name="product_view"),
]
utils.py
import json
from .models import *
def cookieCart(request):
try:
cart = json.loads(request.COOKIES['cart'])
except:
cart = {}
print('CART:', cart)
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']
for i in cart:
try:
cartItems += cart[i]['quantity']
product = Product.objects.get(id=i)
total = (product.price * cart[i]['quantity'])
order['get_cart_total'] += total
order['get_cart_items'] += cart[i]['quantity']
item = {
'id':product.id,
'product':{
'id':product.id,
'name':product.name,
'price':product.price,
'imageURL':product.imageURL
},
'quantity':cart[i]['quantity'],
'digital':product.digital,
'get_total':total,
}
items.append(item)
if product.digital == False:
order['shipping'] = True
except:
pass
return {'cartItems':cartItems ,'order':order, 'items':items}
def cartData(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
cookieData = cookieCart(request)
cartItems = cookieData['cartItems']
order = cookieData['order']
items = cookieData['items']
return {'cartItems':cartItems ,'order':order, 'items':items}
def guestOrder(request, data):
name = data['form']['name']
email = data['form']['email']
cookieData = cookieCart(request)
items = cookieData['items']
customer, created = Customer.objects.get_or_create(
email=email,
)
customer.name = name
customer.save()
order = Order.objects.create(
customer=customer,
complete=False,
)
for item in items:
product = Product.objects.get(id=item['id'])
orderItem = OrderItem.objects.create(
product=product,
order=order,
quantity=item['quantity'],
)
return customer, order
def cookieWishlist(request):
try:
wishlist = json.loads(request.COOKIES['wishlist'])
except:
wishlist = {}
print('WISHLIST:', wishlist)
witems = []
wish = { 'get_wish_items': 0, 'shipping': False}
wishItems = wish['get_wish_items']
for i in wishlist:
try:
wishItems += wishlist[i]['quantity']
product = Product.objects.get(id=i)
wish['get_wish_items'] += wishlist[i]['quantity']
witem = {
'id': product.id,
'product': {
'id': product.id,
'name': product.name,
'price': product.price,
'imageURL': product.imageURL
},
'quantity': wishlist[i]['quantity'],
'status': product.status,
}
witems.append(witem)
except:
pass
return {'wishItems': wishItems, 'wish': wish, 'witems': witems}
def wishData(request):
if request.user.is_authenticated:
customer = request.user.customer
wish, created = Wish.objects.get_or_create(customer=customer, complete=False)
witems = wish.wishitem_set.all()
wishItems = wish.get_wish_items
else:
cookieData = cookieWishlist(request)
wishItems = cookieData['wishItems']
wish = cookieData['wish']
witems = cookieData['witems']
return {'wishItems': wishItems, 'wish': wish, 'witems': witems}
and views.py
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db.models import Max,Min
from django.template.loader import render_to_string
import json
import datetime
from .models import *
from .forms import CreateUserForm, UserUpdateForm
from .utils import cartData, guestOrder, wishData
def store(request):
data = cartData(request)
cartItems = data['cartItems']
data1 = wishData(request)
wishItems = data1['wishItems']
products = Product.objects.all()
minMaxPrice = Product.objects.aggregate(Min('price'), Max('price'))
color = Color.objects.all()
size = Size.objects.all()
brand = Brand.objects.all()
context = {'products':products, 'cartItems':cartItems, 'wishItems':wishItems,'color':color, 'size':size, 'brand':brand, 'minMaxPrice':minMaxPrice}
return render(request, 'store/store.html', context)
def cart(request):
data = cartData(request)
cartItems = data['cartItems']
data1 = wishData(request)
wishItems = data1['wishItems']
order = data['order']
items = data['items']
context = {'items': items, 'order': order, 'cartItems': cartItems, 'wishItems': wishItems}
return render(request, 'store/cart.html', context)
def wishlist(request):
data1 = wishData(request)
wishItems = data1['wishItems']
data = cartData(request)
cartItems = data['cartItems']
wish = data1['wish']
witems = data1['witems']
context = {'wishItems': wishItems,'cartItems': cartItems, 'witems': witems, 'wish': wish}
return render(request, 'store/wishlist.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 updateWishItem(request):
data1 = json.loads(request.body)
productId = data1['productId']
action = data1['action']
print('Action:', action)
print('Product:', productId)
customer = request.user.customer
product = Product.objects.get(id=productId)
wish, created = Wish.objects.get_or_create(customer=customer, complete=False)
wishItem, created = WishItem.objects.get_or_create(wish=wish, product=product)
if action == 'add':
if wishItem.quantity != 1:
wishItem.quantity = (wishItem.quantity + 1)
else:
wishItem.quantity = (wishItem.quantity + 0)
elif action == 'remove':
wishItem.quantity = (wishItem.quantity - 1)
wishItem.save()
if wishItem.quantity <= 0:
wishItem.delete()
return JsonResponse('Item was added', safe=False)
I want products to be added to the cart and not to the wishlist. Products added to the wishlist have the property of a cart. In the wishlist, I have a restriction on adding products, but there is no such restriction in the cart.
for example, I can only add one product of a certain type to a wishlist. But if I’m not logged in, I can add an infinite number to the wishlist (even by clicking on “add to cart”)