Reputation: 65
I am trying to add a product into my cart , but the product is not being able to add . AffProduct Model is the model where all the details of the product is being stored. Whenever I click on the 'Add To Cart' button the pages are being rendered and all the css and html elements being also renderd , but the product is not being added.
Models.py
class AffProduct(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='foo')
product_title = models.CharField(max_length=255)
uid = models.IntegerField(primary_key=True)
specification = models.CharField(max_length=255)
sale_price = models.IntegerField()
discount = models.IntegerField()
img1 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/")
img2 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/")
promote_method = models.TextChoices
terms_conditions = models.CharField(max_length=255, null=True)
promote_method = models.CharField(
max_length=20,
choices=promote_choices,
default='PPC'
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
This is my CartAdd View:
@login_required
@require_POST
def CartAdd(request, uid):
cart = Cart(request)
product = get_object_or_404(AffProduct, uid=uid)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update'])
return redirect('CartDetail')
This is my CartAddProductForm
from django import forms
from .models import Order
PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]
class CartAddProductForm(forms.Form):
quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int, label="quantity")
update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)
The template where i have been trying to render
{% block content %} <h1>Your cart cargo </h1>
<table border="1px" class="table-cart">
<thead>
<tr>
<th>Image</th>
<th>Product</th>
<th>Quantity</th>
<th>Delete</th>
<th>Price</th>
<th>Full Price</th>
</tr>
</thead>
<tbody> {% for item in cart %} {% with product=item.product %}
<tr>
<td class="cart-img"><a href="{{ product.get_absolute_url }}"> <img class="img-responsive"
src="{{ product.img1.url }}"/> </a></td>
<td>{{ product.product_title }}</td>
<td>
<form CartAdd action="{% url "
" product.uid %}" method="post" class="add"> {{ item.update_quantity_form.quantity }} {{
item.update_quantity_form.update }} {% csrf_token %} <input type="submit"
value=" Refresh "> </form>
</td>
<td><a CartRemove href="{% url "" product.uid %}"> Delete </a></td>
<td class="num">{{ item.sale_price }}</td>
<td class="num">{{ item.total_price }}</td>
</tr>
{% endwith %} {% endfor %}
<tr class="total">
<td> Total</td>
<td colspan="4"></td>
<td class="num">{{ cart.get_total_price_after_discount|floatformat:"2" }}</td>
</tr>
</tbody>
</table>
<p> Apply coupon </p>
<form action="" class="add" method="post"> {% csrf_token %} {{ cupon_apply_form }}
<input type="submit" value=" Refresh "></form>
<p class="text-right"><a class="btn btn-light"
href="{% url 'productdetails' %}"> Continue Shopping </a> <a class="btn" href="">
Checkout </a></p> {% endblock %}
And below is the cart.py
from decimal import Decimal
from django.conf import settings
from affiliation.models import AffProduct
#from cupons.models import Cupon
class Cart(object):
def __init__(self, request):
# User cart initialization
self.session = request.session
#self.cupon_id = self.session.get('cupon_id')
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
# Save the user's cart to the session
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
# Adding an item to the user's cart or updating the item quantity
def add(self, product, quantity=1, update_quantity=False):
product_id = str(product.uid)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0,
'price': str(product.sale_price)}
if update_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
# Saving data to a session
def save(self):
self.session[settings.CART_SESSION_ID] = self.cart
# We indicate that the session has been changed
self.session.modified = True
def remove(self, product):
product_id = str(product.uid)
if product_id in self.cart:
del self.cart[product_id]
self.save()
# Iteration on loads
def __iter__(self):
product_ids = self.cart.keys()
products = AffProduct.objects.filter(uid__in=product_ids)
for product in products:
self.cart[str(product.uid)]['product'] = product
for item in self.cart.values():
item['sale_price'] = Decimal(item['sale_price'])
item['total_price'] = item['sale_price'] * item['quantity']
yield item
# Number of goods
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def get_total_price(self):
return sum(Decimal(item['sale_price']) * item['quantity'] for item in self.cart.values())
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
#@property
#def cupon(self):
# if self.cupon_id:
# return Cupon.objects.get(id=self.cupon_id)
# return None
#def get_discount(self):
# if self.cupon:
# return (self.cupon.discount / Decimal('100')) * self.get_total_price()
# return Decimal('0')
def get_total_price_after_discount(self):
return self.get_total_price()
#return self.get_total_price() - self.get_discount()
Below is the urls:
path(r'^add/(?P<uid>\d+)/$', views.CartAdd, name='CartAdd'),
Upvotes: 1
Views: 106
Reputation: 172
You have to save it like this then the product will be added
cart(product=product, quantity=cd['quantity'], update_quantity=cd['update']).save()
There is a quicker method though:
Instead of saying cart = Cart(request)
you can say something like this:
Cart(product=product, quantity=cd['quantity'], update_quantity=cd['update']).save()
here use directly Cart model to save changes!
Upvotes: 2