Python and Django: Building an E-Commerce Site

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting up Django
  4. Creating the Models
  5. Creating Views and Templates
  6. Adding Functionality
  7. 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:

  1. Install Python: Visit the Python website and download the latest version of Python. Follow the installation instructions for your operating system.

  2. Install Django: Open your command-line interface and run the following command:

    pip install django
    

    This 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:

  1. Create a new Django project:

    django-admin startproject ecommerce
    

    This will create a new directory named “ecommerce” with the basic project structure.

  2. Change into the project directory:

    cd ecommerce
    
  3. Create a new Django app:

    python manage.py startapp store
    

    This will create a new directory named “store” inside the project directory, which will contain our app’s code.

  4. Configure the database: Open the settings.py file inside the ecommerce directory and update the DATABASES section 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.

  1. Open the models.py file inside the store directory.

  2. Import the necessary Django modules:

    from django.db import models
    
  3. Define the Category model:

    class Category(models.Model):
        name = models.CharField(max_length=100)
       
        def __str__(self):
            return self.name
    

    The Category model represents the different categories of products in our store. It has a name field of type CharField which will store the category name.

  4. Define the Product model:

    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.name
    

    The Product model represents a product in our store. It has a name field for the product name, a price field of type DecimalField to store the product price, and a category field which is a foreign key to the Category model.

Creating Views and Templates

In this step, we will create the views and templates for our e-commerce site.

  1. Create a new file named views.py inside the store directory.

  2. Import the necessary Django modules:

    from django.shortcuts import render
    from .models import Product
    
  3. Define the home view:

    def home(request):
        products = Product.objects.all()
        return render(request, 'store/home.html', {'products': products})
    

    The home view retrieves all the products from the database and passes them to the home.html template.

  4. Create a new directory named templates inside the store directory, if it doesn’t already exist.

  5. Create a new file named home.html inside the templates/store directory.

  6. Add the following code to the home.html file:

       
    

    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.

  1. Create a new file named urls.py inside the store directory.

  2. Add the following code to the urls.py file:

    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.

  3. Open the urls.py file inside the ecommerce directory and update the urlpatterns list:

    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.

  4. Start the development server:

    python manage.py runserver
    

    This will start the development server on your local machine.

  5. Open your browser and navigate to http://127.0.0.1:8000/. You should see the list of products that were defined in the home.html template.

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!