shopping app consolidated
templates
Searchapp
Cart
GitHub Shopping
GitHub Shopping
app --> Shopping app details only
pro --> settings .py
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'template')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'shopingapp.context_processors.menu_links', 'cart.context_processors.counter', ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'shopingapp', 'USER': 'root', 'PASSWORD': '', } } STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
pro --> url.py
from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include import search_app urlpatterns = [ path('admin/', admin.site.urls), path('shop/', include('shopingapp.urls')), path('search/', include('search_app.urls')), path('cart/', include('cart.urls')), path('/', include('shopingapp.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,
app (shoppping) --> url.py
from django.urls import path, include from . import views #Name space is shop app_name='shop' urlpatterns = [ path('', views.allProdCat, name='allProdCat'), path('<slug:c_slug>/', views.allProdCat, name='products_by_category'), path('<slug:c_slug>/<slug:product_slug>/', views.proDetail, name='prodCatdetail') ]
app (shoppping) --> models.py
from django.db import models from django.urls import reverse # Create your models here. class Category(models.Model): objects = None name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='category', blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('shop:products_by_category', args=[self.slug]) def __str__(self): return '{}'.format(self.name) class Product(models.Model): objects = None name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='product', blank=True) stock= models.IntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now=True) update = models.DateTimeField(auto_now=True) # product details get urls def get_url(self): return reverse('shop:prodCatdetail', args=[self.category.slug, self.slug]) class Meta: ordering = ('name',) verbose_name = 'product' verbose_name_plural = 'products' def __str__(self): return '{}'.format(self.name)
app (shoppping) --> admin.py
from django.contrib import admin # Register your models here. from . models import Category, Product class CategoryAdmin(admin.ModelAdmin): list_display = ['name','slug'] prepopulated_fields = {'slug':('name',)} admin.site.register(Category,CategoryAdmin) class ProductAdmin(admin.ModelAdmin): list_display = ['name','price','stock','available','created','update'] list_editable = ['price','stock','available'] prepopulated_fields = {'slug':('name',)} list_per_page = 20 admin.site.register(Product, ProductAdmin)
app (shoppping) --> views.py
from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from . models import Category, Product # Vertual Env: shop # super user, shop sh1234 # All product category. def allProdCat(request, c_slug=None): global page c_page=None products_list=None if c_slug!=None: c_page=get_object_or_404(Category, slug=c_slug) products_list=Product.objects.all().filter(category=c_page, available=True) else: products_list=Product.objects.all().filter(available=True) paginator=Paginator(products_list, 4) try: page = int(request.GET.get('page','3')) except: page=3 try: products=paginator.page(page) except (EmptyPage, InvalidPage): products=paginator.page(paginator.num_pages) return render(request, "category.html", {'category': c_page, 'products': products}) # To display the product def proDetail(request, c_slug, product_slug): try: product=Product.objects.get(category__slug=c_slug, slug=product_slug) except Exception as e: raise e return render(request, 'product.html', {'product': product})
app (shoppping) --> context_processors.py
from . models import Category def menu_links(request): links=Category.objects.all() return dict(links=links)
templates
templates --> base.html
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="description" content="{% block metadescription %}{% endblock %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <link rel="stylesheet" href="{% static '/css/custom.css' %}"> <title>{% block title %}{% endblock %}</title> </head> <body> <div class="container"> {% include 'header.html' %} {% include 'navbar.html' %} {% block content %} {% endblock %} </div> <div> {% include 'footer.html' %} </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="{% static '/js/bootstrap.bundle.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/popper.min.js' %}"></script> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </body> </html>
templates --> hedder.html
{% load static %} <header> <center> <a href="{% url 'shop:allProdCat' %}"><img src="{% static 'img/logo.png' %}" alt="LogImage" height="150px" width="150px"></a> </center> </header>
templates --> navbar.html
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item dropdown {% if shop in request.path %} active {% endif %}"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Shop </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="{% url 'shop:allProdCat' %}">All Product</a></li> {% for cat in links %} <li><a class="dropdown-item" href="{{cat.get_url}}">{{cat.name}}</a></li> {% endfor %} </ul> </li> {% if item_count > 0 %} <li class="nav-item"> <a class="nav-link" href="{% url 'cart:cart_detail' %}">Your Cart({{item_count}})</a> </li> {% endif %} </ul> <form class="d-flex" action="{% url 'search_app:SearchResult' %}" method="get"> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="Search" name="q" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav>
templates --> footer.html
templates --> category.html
{% extends 'base.html' %} {% load static %} <!---metadescription start---> {% block metadescription %} {% if category %} {{ category.description|truncatewords:155 }} {% else %} Welcome to BroadWay online store for any time any were. {% endif %} {% endblock %} <!---metadescription start---> <!--Header/title start---> {% block title %} {% if category %} {{ category.name }} - BroadWay online Store {% else %} See our new Collections - ABC Store . {% endif %} {% endblock %} <!--Header/title end---> <!--block content from base start---> {% block content %} {% if category %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!--NAV BAR LINKS ADD START ---> <div> <div> <div> <p>> <a href="{% url 'shop:allProdCat' %}">Our Product Collections</a></p> </div> </div> </div> {% endif %} <div class="mx-auto"> {% if category %} <img src="{{category.image.url}}" alt="{{category.name}}" height="300px" width="100%"> </div> <br> <div> <h1 class="text-center my_title">{{category.name}}</h1> <p class="text-justify">{{category.description}}</p> </div> {% else %} <!--NAV BAR LINKS ADD END ---> <!--BNNER ---> <div> <img src="{% static 'img/banner.png' %}" alt="our_products" height="300px" width="100%"> </div> <br> <div> <h1 class="text-center my_title">Our product Collections</h1> <p class="text-justify">Our product CollectionsOur product Collections,t CollectionsOur product </p> </div> {% endif %} <!---product list start --> <div class="mx-auto"> <div class="row"> {% for product in products.object_list %} <div class="col-sm"> <div class="card" style="width: 18rem;"> <a href="{{product.get_url}}"><img class="card-img-top" src="{{product.image.url}}" alt="{{product.name}}"></a> <div class="card-body"> <h4 class="card-text">{{product.name}}</h4> <h6 class="card-text">₹ {{product.price}}</h6> </div> </div> </div> {% endfor %} </div> </div> <!---product list end--> <!--Paginator start for page number---> <div class="mx-auto"> <hr> {% if products.paginator.num_pages > 1 %} <div class="text-center"> {% for pg in products.paginator.page_range %} <a href="?page={{pg}}" class="btn btn-light btn-sm {% if products.number == pg %} active {% endif %}">{{pg}}</a> {% endfor %} </div> {% endif %} <hr> </div> {% endblock %} <!--Paginator End for page number--->
templates --> product.html
{% extends 'base.html' %} {% load static %} <!---metadescription start---> {% block metadescription %} {{ product.description|truncatewords:155 }} {% endblock %} <!---metadescription start---> <!--Header/title start---> {% block title %} {% if category %} {{ product.name }} - BroadWay online Store {% endif %} {% endblock %} {% block content %} <div> <div> <p><a href="{% url 'shop:allProdCat' %}">Home</a> | <a href="{{product.category.get_url}}">{{product.category}}</a>{{product.name}}</p> </div> </div> <div class="container"> <div class="row"> <div class="col"> <img src="{{product.image.url}}" alt="{{product.name}}" height="550px" width="100%"> </div> <div class="col"> <h1>{{product.name}}</h1> <h4>Price: ₹ {{product.price}}</h4> <h6><u>Product Description</u></h6> <p>{{product.description}}</p> {% if product.stock <= 0 %} <p> OUT OF STOCK</p> {% else %} <a class="btn btn-success" href="{% url 'cart:add_cart' product.id%}">Add to Cart</a> {% endif %} </div> </div> </div> {% endblock %}
app --> Searchapp
Searchapp --> urls.py
from django.urls import path from . import views app_name= 'search_app' urlpatterns=[ path('', views.SearchResult, name='SearchResult') ]
Searchapp --> views.py
from django.shortcuts import render from shopingapp.models import Product from django.db.models import Q # Create your views here. def SearchResult(request): products = None query = None if 'q' in request.GET: query = request.GET.get('q') products = Product.objects.all().filter(Q(name__contains=query) | Q(description__contains=query)) return render(request, 'search.html', {'query' : query, 'products': products})
templates for Searchapp --> search.html
{% extends 'base.html' %} {% load static %} {% block metadescription %} We have variety of products. {% endblock %} {% block title %} Search {% endblock %} {% block content %} <div> <p class="text-center my_search_text">You have searched for: <b>"{{query}}"</b></p> </div> <!---product list start --> <div class="mx-auto"> <div class="row"> {% for product in products %} <div class="col-sm"> <div class="card" style="width: 18rem;"> <a href="{{product.get_url}}"><img class="card-img-top" src="{{product.image.url}}" alt="{{product.name}}"></a> <div class="card-body"> <h4 class="card-text">{{product.name}}</h4> <h6 class="card-text">₹ {{product.price}}</h6> </div> </div> </div> </div> </div> {% empty %} <div class="row mx-auto"> <p class="text-center my_search_text"> Sorry, Zero Result fond.</p> </div> {% endfor %} <!---product list end--> {% endblock %}
app --> Cart
Cartapp --> urls.py
from django.urls import path from . import views #name space: cart app_name= 'cart' urlpatterns=[ path('add/<int:product_id>/', views.add_cart, name='add_cart'), path('', views.cart_detail, name='cart_detail'), path('remove/<int:product_id>/', views.cart_remove, name='cart_remove'), path('full_remove/<int:product_id>/', views.full_remove, name='full_remove') ]
Cartapp --> views.py
from django.shortcuts import render, redirect, get_object_or_404 from shopingapp.models import Product from . models import Cart, CartItem from django.core.exceptions import ObjectDoesNotExist # Create your views here. def _cart_id(request): cart=request.session.session_key if not cart: cart=request.session.create() return cart def add_cart(request, product_id): product=Product.objects.get(id=product_id) try: cart=Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart=Cart.objects.create( cart_id=_cart_id(request) ) cart.save(), try: cart_item=CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity +=1 cart_item.save() except CartItem.DoesNotExist: cart_item=CartItem.objects.create( product=product, quantity=1, cart=cart ) cart_item.save() return redirect('cart:cart_detail') def cart_detail(request, total=0, counter=0, cart_items=None): try: cart=Cart.objects.get(cart_id=_cart_id(request)) cart_items=CartItem.objects.filter(cart=cart, active=True) for cart_item in cart_items: total+=(cart_item.product.price * cart_item.quantity) counter +=cart_item.quantity except ObjectDoesNotExist: pass return render(request, 'cart.html', dict(cart_items=cart_items, total=total, counter=counter)) def cart_remove(request, product_id): cart=Cart.objects.get(cart_id= _cart_id(request)) product=get_object_or_404(Product, id=product_id) cart_item=CartItem.objects.get(product=product, cart=cart) if cart_item.quantity >1: cart_item.quantity -=1 cart_item.save() else: cart_item .delete() return redirect('cart:cart_detail') def full_remove(request, product_id): cart = Cart.objects.get(cart_id=_cart_id(request)) product = get_object_or_404(Product, id=product_id) cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.delete() return redirect('cart:cart_detail')
template for Cartapp --> cart.html
{% extends 'base.html' %} {% load static %} {% block metadescription %} This is your Cart Page. procede to review your items and place the order {% endblock %} {% block title %} Cart - Broadway Pvt LMT. {% endblock %} {% block content %} <!---if the cart is empty and else START--> {% if not cart_items %} <script src="https://kit.fontawesome.com/a076d05399.js"></script> <div> <div class="text-center"> <br> <h2 class="text-center">Your Shoping cart is empty.</h2> <br> <p class="text-center">Add to cart <a href="{% url 'shop:allProdCart' %}"> here</a> to continue home page.</p> </div> </div> {% else %} <div> <div class="text-center"> <br> <h2>Your Shopping Cart.</h2> <br> </div> </div> <!----boostap table start---> <div class="row"> <div class="col-8"> <table class="table"> <thead> <tr> <th></th> <th colspan="4" style="text-align: center;">Your Items</th> </tr> </thead> <tbody> {% for cart_item in cart_items %} <tr> <th scope="row"><a href="cart_item.product.get_absolute_url"> <img src="{{cart_item.product.image.url}}" alt="product" class="float-left" height="100px" width="100px"></a></th> <td> {{cart_item.product.name}} <br> SKU:{{cart_item.product.id}} <br> Product: {{cart_item}} <br> Qty: {{cart_item.quantity}} x Price: $ {{cart_item.product.price}} </td> <td> $ {{cart_item.sub_total}} </td> {% if cart_item.quantity < cart_item.product.stock %} <td> <a href="{% url 'cart:add_cart' cart_item.product.id %}"> + </a><br> <a href="{% url 'cart:cart_remove' cart_item.product.id %}" >-</a><br> <a href="{% url 'cart:full_remove' cart_item.product.id %}">Dele</a><br> </td> {% else %} <td> <a href="{% url 'cart:cart_remove' cart_item.product.id %}">-</a><br> <a href="{% url 'cart:full_remove' cart_item.product.id %}">Del</a> </td> {% endif %} </tr> {% endfor %} </tbody> </table> </div> <!----boostap table start---> <!---Checkout and back to home menu START----> <div class="col-4" style="padding-top: 40px;"> <div class="card border-dark mb-3" style="width: 100%;"> <div class="card-header"><strong>Checkot </strong></div> <div class="card-body text-dark"> <p class="card-title">Please review your shopping items before Checkout the order.</p> <h5 class="card-title">Your Total amount is, <strong>$ {{total}}</strong></h5> <a href="{% url 'shop:allProdCat' %}" class="btn btn-secondary btn-block">Continue shopping</a> </div> </div> </div> </div> {% endif %} <!---if the cart is empty and else END--> {% endblock %} <!---Checkout and back to home menu end---->
No comments