from django.db import models
from django.urls import reverse
class Note_Manufacturer(models.Model):
name = models.CharField(verbose_name='Manufacturer', max_length=50,
blank=True, null=True)
country = models.CharField(verbose_name='Country', max_length=50,
blank=True, null=True)
def __str__(self):
return (str(self.name))
def note_manufacturer(self):
return reverse('note_manufacturer_detail', args=[str(self.pk)])
class Notebook(models.Model):
brand = models.ForeignKey(Note_Manufacturer, verbose_name='Manufacturer',
related_name='notebook_list',
max_length=20,
on_delete=models.CASCADE, null=True)
name = models.CharField(verbose_name='Model', max_length=50,
blank=True, null=True, unique=True)
color = models.CharField(verbose_name='Color', max_length=50,
blank=True, null=True)
style = models.CharField(verbose_name='Category', max_length=50,
blank=True, null=True)
price = models.DecimalField(verbose_name='Price', max_digits=10,
decimal_places=2, null=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('note_product_detail', args=[str(self.pk)])
class Phone_Manufacturer(models.Model):
name = models.CharField(verbose_name='Manufacturer', max_length=50,
blank=True, null=True)
country = models.CharField(verbose_name='Country', max_length=50,
blank=True, null=True)
def __str__(self):
return (str(self.name))
def phone_manufacturer(self):
return reverse('phone_manufacturer_detail', args=[str(self.pk)])
class Phone(models.Model):
brand = models.ForeignKey(Phone_Manufacturer, verbose_name='Manufacturer',
related_name='phone_list',
max_length=20,
on_delete=models.CASCADE, null=True)
name = models.CharField(verbose_name='Model', max_length=50,
blank=True, null=True, unique=True)
color = models.CharField(verbose_name='Color', max_length=50,
blank=True, null=True)
style = models.CharField(verbose_name='Category', max_length=50,
blank=True, null=True)
price = models.DecimalField(verbose_name='Price', max_digits=10,
decimal_places=2, null=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('phone_product_detail', args=[str(self.pk)])
from django.shortcuts import render, redirect, get_object_or_404
from .cart import Cart
from .forms import CartAddForm
from my_first_site.note.models import Notebook
from my_first_site.phone.models import Phone
from orders.models import OrderItem
import itertools
def cart_detail(request):
cart = Cart(request)
for item in cart:
item['update_quantity_form'] = CartAddForm(
initial={'quantity': item['quantity'], 'update': True})
return render(request, 'cart_detail.html',
{
'cart': cart,
})
from decimal import Decimal
from django.conf import settings
from my_first_site.note.models import Notebook
from my_first_site.phone.models import Phone
class Cart(object):
def __init__(self, request):
# get the session object
self.session = request.session
# define the session and call it cart
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
# save the shopping cart in session
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def add(self, product, quantity=1, update_quantity=False):
# convert item id into a string to use JSON
product_id = str(product.id)
if product_id not in self.cart:
# if the item is not in the basket,
# create a dictionary with number of items is 0, and the price converted to a string
self.cart[product_id] = {
'quantity': 0, 'price': str(product.price)}
# update the item quantity in the basket
if update_quantity:
self.cart[product_id]['quantity'] = quantity
else:
# increase the number of items in the cart
self.cart[product_id]['quantity'] += quantity
self.save()
def save(self):
# update the session cart
self.session[settings.CART_SESSION_ID] = self.cart
# specify that session changed
self.session.modified = True
def remove(self, product):
# get item id
product_id = str(product.id)
if product_id in self.cart:
self.cart[product_id]['quantity'] -= 1
if self.cart[product_id]['quantity'] <= 1:
# if the item in the cart, then remove
del self.cart[product_id]
self.save()
def __iter__(self):
# iterates through the items in the recycle bin and retrieving them from the database
product_ids = self.cart.keys()
# get the object item and adding it to the cart
notes = Notebook.objects.filter(id__in=product_ids)
phones = Phone.objects.filter(id__in=product_ids)
for note in notes:
self.cart[str(note.id)]['note'] = note
for phone in phones:
self.cart[str(phone.id)]['phone'] = phone
for item in self.cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
def __len__(self):
# count of all items in your shopping cart
return sum(item['quantity'] for item in self.cart.values())
def get_total_price(self):
# counting the cost of the items in the cart
return sum(Decimal(
item['price']) * item['quantity']
for item in self.cart.values())
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
{% extends 'index.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% block title %}
<title>shopping Cart</title>
{% endblock %}
{% block content%}
<h2>Cart</h2>
{% if user.is_authenticated %}
<h2><a href="{% url 'order_create' %}">Checkout</a></h2>
<div class="cart_products">
{% if cart|length > 0 %}
{% for item in cart %}
<div class="cart_product_item">
{% if item.note.pk %}
<div class="item_name">
the <h3>Item: {{ item.note.brand }} {{ item.note.name }}</h3>
</div>
<div class="item_body">
<p>
ID: {{ item.note.pk }}
</p>
<p>
Price: {{ item.note.price }}
</p>
<p>
Quantity: {{ item.quantity }} | Sum: {{ item.total_price }}
</p>
<p><a href="{{ item.note.get_absolute_url }}">product Description</a></p>
</div>
<div class="add">
<form action="{% url 'cart_add_note' item.note.pk %}" method="POST">
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
{% csrf_token %}
<hr>
<input type="submit" value="add to cart" class="btn btn-primary btn-block">
<a href="{% url 'cart_remove_note' item.note.pk %}" class="btn btn-primary btn-block">Remove from
basket</a>
</form>
</div>
{% endif %}
{% if item.phone.pk %}
<div class="item_name">
the <h3>Item: {{ item.phone.brand }} {{ item.phone.name }}</h3>
</div>
<div class="item_body">
<p>
ID: {{ item.phone.pk }}
</p>
<p>
Price: {{ item.phone.price }}
</p>
<p>
Quantity: {{ item.quantity }} | Sum: {{ item.total_price }}
</p>
<!-- phone is a product model Notebook, she called get_absolute_url method -->
<p><a href="{{ item.phone.get_absolute_url }}">product Description</a></p>
</div>
<div class="add">
<form action="{% url 'cart_add_phone' item.phone.pk %}" method="POST">
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
{% csrf_token %}
<hr>
<input type="submit" value="add to cart" class="btn btn-primary btn-block">
<a href="{% url 'cart_remove_phone' item.phone.pk %}" class="btn btn-primary btn-block">Remove from
basket</a>
</form>
</div>
{% endif %}
</div>
{% endfor %}
</div>
{% else %}
<p>Cart is empty</p>
{% endif %}
{% endif %}
{% endblock %}
Cart.cart
will only be one record because the keys are the same. This is a mistake again.def __iter__(self):
# iterates through the items in the recycle bin and retrieving them from the database
product_ids = self.cart.keys() # [5]
# get the object item and adding it to the cart
notes = Notebook.objects.filter(id__in=product_ids) # Notebook.objects.filter(id__in=[5])
phones = Phone.objects.filter(id__in=product_ids) # Phone.objects.filter(id__in=[5])
id == 5
. This is a mistake or two.Cart
. For example, you can replace the keys on these:product_id = f'{product._meta.app_label}.{product._meta.object_name}.{product.pk}'
product_id = f'{product._meta.app_label}.{product._meta.object_name}.{product.pk}'
from django.apps.registry.Apps import get_model
def get_object_from_string(string):
app_label, model_name, pk = string.split('.')
model = get_model(app_label, model_name)
return model.objects.get(pk=int(pk))
phone = get_object_from_string('cart.Phone.123')
get_object_from_string
get from the string instances of product models. commented on April 7th 20 at 15:52Find more questions by tags Django
Read more does not work, because it's a skill "domain modeling". Partly you can obtain by reading the textbooks on relational databases, partly from experience will come. - Hershe commented on April 7th 20 at 15:47