Table of Contents
- Introduction
- Prerequisites
- Setting up Django
- Creating the Models
- Creating Views and Templates
- Adding Functionality
- Conclusion
Introduction
In this tutorial, we will learn how to build an e-commerce site using Python and the Django web framework. By the end of this tutorial, you will have a working e-commerce site with product listings, a shopping cart, and a checkout process.
Prerequisites
Before starting this tutorial, you should have a basic understanding of Python programming language and web development concepts. Additionally, you will need to have Python and Django installed on your local machine. If you haven’t installed these, follow the steps below:
-
Install Python: Visit the Python website and download the latest version of Python. Follow the installation instructions for your operating system.
-
Install Django: Open your command-line interface and run the following command:
pip install djangoThis will install the latest version of Django.
Setting up Django
Now that we have Python and Django installed, let’s set up our Django project. Open your command-line interface and follow these steps:
-
Create a new Django project:
django-admin startproject ecommerceThis will create a new directory named “ecommerce” with the basic project structure.
-
Change into the project directory:
cd ecommerce -
Create a new Django app:
python manage.py startapp storeThis will create a new directory named “store” inside the project directory, which will contain our app’s code.
-
Configure the database: Open the
settings.pyfile inside theecommercedirectory and update theDATABASESsection with your database credentials. By default, Django uses SQLite as the database backend.
Creating the Models
Now that our project is set up, let’s define the models for our e-commerce site. Models represent the data structures of our application.
-
Open the
models.pyfile inside thestoredirectory. -
Import the necessary Django modules:
from django.db import models -
Define the
Categorymodel:class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.nameThe
Categorymodel represents the different categories of products in our store. It has anamefield of typeCharFieldwhich will store the category name. -
Define the
Productmodel:class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.nameThe
Productmodel represents a product in our store. It has anamefield for the product name, apricefield of typeDecimalFieldto store the product price, and acategoryfield which is a foreign key to theCategorymodel.
Creating Views and Templates
In this step, we will create the views and templates for our e-commerce site.
-
Create a new file named
views.pyinside thestoredirectory. -
Import the necessary Django modules:
from django.shortcuts import render from .models import Product -
Define the
homeview:def home(request): products = Product.objects.all() return render(request, 'store/home.html', {'products': products})The
homeview retrieves all the products from the database and passes them to thehome.htmltemplate. -
Create a new directory named
templatesinside thestoredirectory, if it doesn’t already exist. -
Create a new file named
home.htmlinside thetemplates/storedirectory. -
Add the following code to the
home.htmlfile:This code will render the name and price of each product in the database.
Adding Functionality
Now that we have the basic structure of our e-commerce site, let’s add some functionality like the shopping cart and checkout process.
-
Create a new file named
urls.pyinside thestoredirectory. -
Add the following code to the
urls.pyfile:from django.urls import path from .views import home urlpatterns = [ path('', home, name='home'), ]This code sets up the URL routes for our views. In this case, we only have one view named
home, which will be mapped to the root URL. -
Open the
urls.pyfile inside theecommercedirectory and update theurlpatternslist:from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')), ]This code includes the URLs from our app into the main project URLs.
-
Start the development server:
python manage.py runserverThis will start the development server on your local machine.
-
Open your browser and navigate to
http://127.0.0.1:8000/. You should see the list of products that were defined in thehome.htmltemplate.
Conclusion
Congratulations! You have successfully built an e-commerce site using Python and Django. In this tutorial, we learned how to set up a Django project, define models, create views and templates, and add basic functionality to our site.
You can further enhance your e-commerce site by adding features like user authentication, product filtering, and payment integration. Django provides many tools and libraries to help you build powerful and secure web applications. Feel free to explore the Django documentation and experiment with different features to customize your site according to your requirements.
Remember to keep practicing and building new projects to strengthen your Python and Django skills. Happy coding!