cart update view - lhmisho/django-eCommerce GitHub Wiki
carts/views.py
from django.shortcuts import render, redirect
from .models import Cart
from products.models import Product
# Create your views here.
# method for create a cart for user.
def cart_home(request):
cart_obj, new_obj = Cart.objects.new_or_get(request)
return render(request, 'carts/cart_home.html', {})
# Update view for cart
def cart_update(request):
product_id = 1
product_obj = Product.objects.get(id=product_id)
cart_obj, new_obj = Cart.objects.new_or_get(request) # we also added this line to products view on get_context_data so that we can add cart to specific product
if product_obj in cart_obj.products.all():
cart_obj.products.remove(product_obj)
else:
cart_obj.products.add(product_obj)
#return redirect(product_obj.get_absolute_url())
return redirect("cart:home")
now we need to pass our cart to product context so that we can add product to our cart
products/views.py
from django.shortcuts import render, get_object_or_404, Http404
from django.views.generic import ListView, DetailView
# importing from .models
from .models import Product
from carts.models import Cart
# featured product section
class ProductFeaturedListView(ListView):
# first way to manage list view
#queryset = Product.objects.all()
template_name = 'products/product_list.html'
# another way to manage listView
def get_queryset(self, *args, **kwargs):
request = self.request
return Product.objects.all().featured()
class ProductFeaturedDetailView(DetailView):
# geting all object form Product
queryset = Product.objects.all().featured()
template_name = 'products/featured-detail.html'
# another way to manage detail view
# def get_queryset(self, *args, **kwargs):
# request = self.request
# return Product.objects.featured()
# slug product section
class ProductSlugDetailView(DetailView):
##########################################################################################
# passing cart to the context so that we can add product to the cart
def get_context_data(self, *args, **kwargs):
context = super(ProductSlugDetailView, self).get_context_data(*args, **kwargs)
request = self.request
cart_obj, new_obj = Cart.objects.new_or_get(request)
context['cart'] = cart_obj
return context
##########################################################################################
# #queryset = Product.objects.all()
template_name = "products/product_detail.html"
def get_object(self, *args, **kwargs):
slug = self.kwargs.get('slug')
try:
instance = Product.objects.get(slug=slug, active=True)
except Product.DoesNotExist:
raise Http404("Product not exist")
except Product.MultipleObjectsReturned:
qs = Product.objects.filter(slug=slug, active=True)
instance = qs.first()
except:
raise Http404("don't bother..")
return instance
# general product section
class ProductListView(ListView):
# first way to manage list view
#queryset = Product.objects.all()
template_name = 'products/product_list.html'
def get_queryset(self, *args, **kwargs):
request = self.request
return Product.objects.all()
def product_list_page(request):
# getting data from products
queryset = Product.objects.all()
context = {
'object_list' : queryset
}
return render(request, 'products/product_list.html', context)
class ProductDetailView(DetailView):
# geting all object form Product
#queryset = Product.objects.all()
template_name = 'products/product_detail.html'
def get_context_data(self, *args, **kwargs):
context = super(ProductDetailView, self).get_context_data(*args,**kwargs)
print(context)
return context
#my custom query for retriving data in detailView
def get_object(self, *args, **kwargs):
#request = self.request
pk = self.kwargs.get('pk')
instance = Product.objects.get_by_id(pk) # my query
print(instance)
if instance is None:
raise Http404("product not found")
return instance
# another way to manage detail view
# def get_queryset(self, *args, **kwargs):
# pk = self.kwargs.get('pk')
# return Product.objects.filter(pk=pk)
def product_detail_page(request,pk=None, *args, **kwargs):
# getting data from products
# instance = Product.objects.get(pk=pk)
# instace = get_object_or_404(Product, pk=pk)
# try:
# instance = Product.objects.get(id=pk)
# except Product.DoesNotExist:
# print("Products doesn't exit")
# raise Http404("Product doesn't exist")
# except:
# print("idiot go anyware else")
# get_by_id is my custom query ...
instance = Product.objects.get_by_id(pk)
print(instance)
if instance is None:
raise Http404("product not found")
# qs = Product.objects.filter(id=pk)
# if qs.count() == 1:
# print(qs)
# instance = qs.first()
# else:
# raise Http404("products doesn't exist")
context = {
'object' : instance
}
return render(request, 'products/product_detail.html', context)
here products/views.py we addded this portion on ProductSlugDetailviews to pass context
##########################################################################################
# passing cart to the context so that we can add product to the cart
def get_context_data(self, *args, **kwargs):
context = super(ProductSlugDetailView, self).get_context_data(*args, **kwargs)
request = self.request
cart_obj, new_obj = Cart.objects.new_or_get(request)
context['cart'] = cart_obj
return context
##########################################################################################
carts/urls.py
from django.urls import path,re_path
from .views import cart_home, cart_update
app_name = 'cart'
urlpatterns = [
..............................
path('update/', cart_update,name='update'),
..............................
]
now it's time to manage products details template ot add or remove cart
products/templates/products/products_details.html
{%include 'base.html'%}
{% block content%}
<div class="container">
<div class="row">
<div class="col-12 col-md-6">
<h1>{{object.title}}</h1>
<h3>{{"Some Title"|title}}</h3>
<p>{{object.timestamp}}</p>
<p>{{object.timestamp|timesince}} ago</p>
<p>{{object.description|linebreaksbr|safe}}</p>
{% if object.image %}
<img src="{{object.image.url}}" alt="image">
{% endif %}
</div>
<div class="col-12 col-md-6">
{{cart}}
<!-- abc should be object -->
{%if object in cart.products.all %}
<button class="btn btn-link">remove?</button>
{%else%}
<button class="btn btn-success">Add to cart</button>
{%endif%}
</div>
</div>
</div>
{% endblock %}
here i add this portion for cart add or remove.
<div class="col-12 col-md-6">
{{cart}}
<!-- abc should be object -->
{%if object in cart.products.all %}
<button class="btn btn-link">remove?</button>
{%else%}
<button class="btn btn-success">Add to cart</button>
{%endif%}
</div>