Django 1 2 E Commerce Legg Jesse Building an Ecommerce Platform with Django 12 A StepbyStep Guide This article will guide you through the process of building a basic ecommerce platform using Django 12 a popular and robust Python framework Well cover the essential components from setting up your development environment to implementing key features like product management cart functionality and payment integration While Django 12 is considered outdated understanding its core principles will provide a strong foundation for working with newer versions of the framework 1 Project Setup Install Python Ensure you have Python installed on your system Download the latest version from httpswwwpythonorgdownloadshttpswwwpythonorgdownloads Install Django Use pip Pythons package installer to install Django 12 bash pip install Django12 Create a New Project Use the djangoadmin command to generate a new Django project bash djangoadmin startproject ecommercestore Navigate to the Project Directory Navigate into the newly created project directory bash cd ecommercestore Create an App Create an app for your ecommerce store bash python managepy startapp products 2 Defining Models Models represent the data structure of your ecommerce store Well start by creating models for products categories and users 2 python productsmodelspy from djangodb import models from djangocontribauthmodels import User class CategorymodelsModel name modelsCharFieldmaxlength255 slug modelsSlugFieldmaxlength255 uniqueTrue def strself return selfname class ProductmodelsModel name modelsCharFieldmaxlength255 slug modelsSlugFieldmaxlength255 uniqueTrue description modelsTextFieldblankTrue price modelsDecimalFieldmaxdigits6 decimalplaces2 image modelsImageFielduploadtoproductsYmd blankTrue category modelsForeignKeyCategory ondeletemodelsCASCADE stock modelsIntegerFielddefault0 available modelsBooleanFielddefaultTrue createdat modelsDateTimeFieldautonowaddTrue updatedat modelsDateTimeFieldautonowTrue def strself return selfname class UserProfilemodelsModel user modelsOneToOneFieldUser ondeletemodelsCASCADE address modelsCharFieldmaxlength255 blankTrue city modelsCharFieldmaxlength255 blankTrue country modelsCharFieldmaxlength255 blankTrue def strself return selfuserusername 3 Creating Views and Templates Views handle the logic of your application while templates provide the presentation layer Well create views for displaying product lists product details and a shopping cart 3 python productsviewspy from djangoshortcuts import render getobjector404 from models import Product Category def productlistrequest categoryslugNone category None products Productobjectsall if categoryslug category getobjector404Category slugcategoryslug products productsfiltercategorycategory context category category products products return renderrequest productsproductlisthtml context def productdetailrequest slug product getobjector404Product slugslug context product product return renderrequest productsproductdetailhtml context Now create the corresponding templates in the templatesproducts directory html templatesproductsproductlisthtml extends basehtml block content Products if category categoryname endif for product in products 4 productname productprice endfor endblock templatesproductsproductdetailhtml extends basehtml block content productname productdescription Price productprice Add to Cart endblock 4 Cart Functionality To implement a shopping cart we can use Djangos builtin session framework to store cart items Well add a cart view to handle adding and removing items from the cart python productsviewspy from djangoshortcuts import render getobjector404 redirect from models import Product def cartrequest cart requestsessiongetcart if requestmethod POST productid requestPOSTgetproductid quantity intrequestPOSTgetquantity 1 if productid product getobjector404Product pkproductid if productid in cart cartproductid quantity else 5 cartproductid quantity requestsessioncart cart context cart cart return renderrequest productscarthtml context def addtocartrequest slug product getobjector404Product slugslug cart requestsessiongetcart if productpk in cart cartproductpk 1 else cartproductpk 1 requestsessioncart cart return redirectcart def removefromcartrequest slug product getobjector404Product slugslug cart requestsessiongetcart if productpk in cart del cartproductpk requestsessioncart cart return redirectcart Create the carthtml template html templatesproductscarthtml extends basehtml block content Your Cart Product Quantity Price 6 for productid quantity in cartitems with productproductidgetobjectProduct productname quantity productprice endwith endfor Proceed to Checkout endblock 5 Checkout and Payment Integration For checkout and payment integration you can utilize thirdparty payment gateways like Stripe PayPal or Braintree Heres a basic outline for integrating Stripe Install Stripe Python Library bash pip install stripe Create a Stripe Account Sign up for a Stripe account at httpsstripecomhttpsstripecom Configure Stripe API Keys Obtain your API keys from your Stripe dashboard and add them to your Django settings file python ecommercestoresettingspy STRIPESECRETKEY YOURSTRIPESECRETKEY STRIPEPUBLISHABLEKEY YOURSTRIPEPUBLISHABLEKEY Create a checkouthtml template html 7 templatesproductscheckouthtml extends basehtml block content Checkout csrftoken Complete Purchase var stripe Stripe STRIPEPUBLISHABLEKEY var elements stripeelements var cardElement elementscreatecard cardElementmountcardelement var form documentquerySelectorform formaddEventListenersubmit functionevent eventpreventDefault stripecreateTokencardElementthenfunctionresult if resulterror Handle error else Send token to server formquerySelectorinputnamestripeTokenvalue resulttokenid formsubmit endblock Create a processpayment view python productsviewspy import stripe def processpaymentrequest 8 if requestmethod POST stripetoken requestPOSTgetstripeToken try charge stripeChargecreate amount1000 Amount in cents currencyusd descriptionEcommerce Purchase sourcestripetoken Handle successful payment return redirectpaymentsuccess except stripeerrorCardError as e Handle card errors return renderrequest productscheckouthtml error ejsonbodyerrormessage except Exception as e Handle other exceptions return renderrequest productscheckouthtml error stre return renderrequest productscheckouthtml 6 Additional Features User Authentication Integrate Djangos builtin authentication system to manage user accounts and permissions Order Management Implement order tracking and management functionality Search and Filtering Allow users to search for products and filter them by category price and other attributes Product Reviews Enable users to leave reviews and ratings for products Shipping and Delivery Integrate shipping services to calculate shipping costs and manage delivery Conclusion Building an ecommerce platform with Django 12 is a rewarding experience that allows you to learn about web development data modeling and business logic This guide provides a foundation for creating a basic ecommerce site You can further enhance it by adding advanced features customizing its appearance and optimizing its performance for scalability Remember to keep up with the latest Django versions and leverage the rich ecosystem of thirdparty packages to simplify development 9