Learn Django by Building a Marketplace

Django is one of the most popular and powerful web frameworks available today. Built with Python, Django makes it easy to construct feature-rich, scalable web applications quickly. Whether you‘re a beginner looking to learn web development or an experienced programmer exploring Python frameworks, Django is an excellent choice.

In this guide, we‘ll walk through how to build a fully-functional online marketplace application with Django from scratch. You‘ll learn the core concepts and common patterns used in Django development by creating a real-world project. By the end, you‘ll have a solid foundation in Django and the confidence to build your own web apps.

Here‘s what we‘ll cover:

  • Setting up a development environment
  • Creating a new Django project and apps
  • Designing the database models
  • Implementing user registration and authentication
  • Building the marketplace functionality
  • Adding a shopping cart and checkout process
  • Creating seller dashboards
  • Implementing product search and filtering
  • Adding user reviews and ratings
  • Discussing advanced topics and additional features
  • Wrapping up and next steps

Let‘s get started!

Setting Up the Development Environment

First, we‘ll get a development environment set up on your local machine. You‘ll need to have Python installed, which you can download from the official Python website if you don‘t have it already.

We recommend using a virtual environment to isolate the dependencies for your Django project. You can create a new virtual environment with the venv module:

python -m venv env

Activate the virtual environment:

source env/bin/activate  # On Windows, use `env\Scripts\activate`

With the virtual environment active, install Django using pip:

pip install django

Creating the Django Project

Now we‘re ready to start a new Django project. In your terminal, run the following command:

django-admin startproject marketplace

This will create a new directory called marketplace with the basic structure of a Django project. Let‘s also create a new app within our project that will handle the core marketplace functionality:

cd marketplace
python manage.py startapp main

The main app is where we‘ll put most of our marketplace code. Make sure to add it to the list of installed apps in the marketplace/settings.py file:

INSTALLED_APPS = [
    ...
    ‘main‘,
]

Designing the Database Models

Next, let‘s consider what database models we‘ll need for our marketplace app. We‘ll define models for:

  • User: the built-in Django user model, extended with a custom user profile
  • Product: represents a product listing in the marketplace
  • Order: represents an order that a user has placed
  • OrderItem: represents an individual product that is part of an order
  • Review: represents a review of a product left by a user

Here‘s an example of what the Product model might look like (in main/models.py):

from django.db import models
from django.contrib.auth.models import User

class Product(models.Model):
    seller = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    quantity = models.IntegerField(default=1)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

We define the fields that describe a product, including a foreign key to the User model to represent the seller, and other details like the name, description, price, and quantity available. The created_at and updated_at fields will automatically store timestamps when a product is created or updated.

We can define similar models for Order, OrderItem, and Review. After creating the models, we need to create a migration and sync the database:

python manage.py makemigrations main
python manage.py migrate

User Registration and Authentication

Most marketplace apps require users to create an account in order to buy and sell products. We can use Django‘s built-in authentication system to handle user registration and login.

We‘ll need a registration form for new users to sign up. Django provides a built-in UserCreationForm that we can extend:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False)
    last_name = forms.CharField(max_length=30, required=False)
    email = forms.EmailField(max_length=254, help_text=‘Required. Enter a valid email address.‘)

    class Meta:
        model = User
        fields = (‘username‘, ‘first_name‘, ‘last_name‘, ‘email‘, ‘password1‘, ‘password2‘, )

We add some additional fields for the user‘s name and email address. Now we can create a view that renders this form and handles user registration:

from django.contrib.auth import login
from django.shortcuts import render, redirect

def register(request):
    if request.method == ‘POST‘:
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect(‘home‘)
    else:
        form = SignUpForm()
    return render(request, ‘registration/register.html‘, {‘form‘: form})

When the form is submitted and valid, we create a new user account and log them in. We‘ll also need a template to display the form (in templates/registration/register.html):

{% extends ‘base.html‘ %}

{% block content %}
  <h2>Sign up</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

Finally, we add URL patterns for the registration and login views in our main urls.py file:

from django.urls import path, include

urlpatterns = [
    ...
    path(‘register/‘, views.register, name=‘register‘),
    path(‘accounts/‘, include(‘django.contrib.auth.urls‘)),
]

Now users can create an account and log in to the marketplace. We can access the currently logged-in user with request.user in our views.

Building the Marketplace

With user registration in place, we can start building out the core marketplace functionality. We‘ll need views, templates, and URL patterns to:

  • Display a list of all products
  • Show the details of an individual product
  • Allow sellers to create new product listings
  • Enable buyers to add products to their cart and place orders
  • Provide seller dashboards for managing products and orders
  • Implement product search and filtering

Here‘s an example of a view that displays a single product:

from django.shortcuts import render, get_object_or_404
from .models import Product

def product_detail(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    return render(request, ‘main/product_detail.html‘, {‘product‘: product})

We use the get_object_or_404 shortcut to retrieve a product by its ID, or raise a 404 error if it doesn‘t exist. Then we render a template that shows the details of the product.

The template (in main/templates/main/product_detail.html) might look something like this:

{% extends ‘base.html‘ %}

{% block content %}

  <p>{{ product.description }}</p>
  <p>Price: ${{ product.price }}</p>
  <p>Seller: {{ product.seller.username }}</p>
  <form method="post" action="{% url ‘add_to_cart‘ product.id %}">
    {% csrf_token %}
    <input type="number" name="quantity" value="1">
    <button type="submit">Add to Cart</button>
  </form>
{% endblock %}

This template displays the product name, description, price, and seller. It also includes a form that allows a buyer to add the product to their shopping cart.

The view for adding a product to the cart might look like this:

from django.shortcuts import redirect
from .models import Order, OrderItem

def add_to_cart(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    order, created = Order.objects.get_or_create(user=request.user, complete=False)
    order_item, created = OrderItem.objects.get_or_create(order=order, product=product)
    order_item.quantity = request.POST[‘quantity‘]
    order_item.save()
    return redirect(‘cart‘)

This view retrieves the user‘s current open order (or creates a new one if it doesn‘t exist), adds the selected product to the order as an OrderItem, and redirects to the shopping cart page.

We can continue building out the rest of the marketplace functionality in a similar way, creating views and templates for listing products, searching and filtering, checking out, leaving reviews, and so on.

Advanced Topics and Additional Features

Once we have the basic marketplace up and running, there are many ways we can enhance and optimize our application. Some advanced topics and additional features to consider:

  • Optimizing performance with caching, database indexes, and eager loading
  • Implementing full-text search with a search backend like Postgres or Elasticsearch
  • Providing an API for programmatic access to the marketplace data
  • Supporting multiple payment gateways and currencies
  • Integrating with a shipping provider to generate shipping labels
  • Sending transactional emails for order confirmations and status updates
  • Implementing a messaging system for buyers and sellers to communicate
  • Enhancing the buyer and seller dashboards with analytics and visualizations
  • Ensuring the application follows security best practices

The great thing about Django is that it provides a solid foundation and ecosystem of packages to help implement these more advanced features. And of course, this is just a starting point – there are endless possibilities for what you can build!

Conclusion and Next Steps

In this guide, we‘ve walked through the process of building an online marketplace application with Django. We set up our development environment, created a new Django project, designed our database models, implemented user registration and authentication, built out the core marketplace functionality, and discussed some advanced topics and additional features.

By following along and creating your own marketplace project, you‘ve gained hands-on experience with Django and learned many of the key concepts and patterns used in web development with this powerful framework. You now have a solid foundation to continue learning and building your own Django applications.

Some next steps to consider:

  • Add more features to your marketplace project, like the ones discussed above
  • Explore other Django packages and integrations to enhance your app
  • Learn about deploying Django applications to production environments
  • Build your own Django projects from scratch to solidify your understanding
  • Dive deeper into advanced Django topics like testing, security, and performance

The Django documentation and community are great resources as you continue on your Django learning journey. There are also many excellent Django books, tutorials, and courses available to help you grow your skills.

Good luck, and happy coding!

Similar Posts