How to Develop Web Applications on Alibaba Cloud with Django Framework

Why Django?

Before we discuss about Django, let’s take a step back to better understand what a web application is. A web application is a set of code written in a programming language that will be rendered on a browser, which typically addresses a well-defined problem. For example, it can be a blog post (like this article!), an e-commerce website, or even a social network.


Defining Our Project

The project we are going to build is an e-commerce web application where people can buy or sell items. For flexibility and maintainability reasons, the project will be split in three independent apps: the Core app, the Cart app and the Payment.

Presenting Each Application

Core Application

As mentioned before, the core app will manage everything related to products (add, modify, remove) we want to sell. The core application is intended to manage all the buying process:

  1. Users (Buyers/Sellers and Administrators)
  2. Products
  3. Product Categories

Cart Application

The cart application will be used to manage the buying and selling process. The specific elements that will be managed here will be:

  1. Buy and Sell options
  2. Cart and CartItems of the client
  3. Adding and removing Products to the Cart

Payment Application

The payment app will give the access to payment gateways, allowing to receive the money given by the clients. It includes:

  1. Payment gateways
  2. Payment processes
  3. Payment APIs integration

Setting Up the Development Environment

Install python 3 and pip

$ python --version
# sudo apt-get install python3
# sudo apt-get install python-pip
# sudo apt-get update
# sudo apt-get install python-dev libpq-dev postgresql postgresql-contrib
# sudo pip install virtualenv
(venv)$ pip install pillow

Starting and Configuring the Project

Create a Virtual Environment and Activate It

This command will create a virtual environment inside the folder venv with python3 as the default python interpreter

$ virtualenv venv --python=python3               
$ cd venv
$ source bin/activate

Install Django in That Virtual Environment

(venv)$ cd venv
(venv)$ pip install django==2.1

Create the Django Project

(venv)$ django-admin startproject buyandsell
  1. this file is used to set core configurations of our app, like database access parameters, defining static file service.
  2. this is the file used to create URL routes from which our application will serve the content we are storing.
  3. this file defines default configurations used by the web server on deployment configurations.
  4. this is the main script that we will use to manage our Django project and its apps (database migrations, tests execution, dev server running)
  5. db.sqlite3: this is the default database that come preconfigured with Django. We will use it only for development purposes, but when the deployment time will come, we will change this database with the PostgreSQL database which is the used database in combination with Django applications.
  6. will be used to generate the admin interface applications.
  7. this file defines the tests that will be ran when testing the app.
  8. this file contents the default configurations of our app.

Initialize the Database by Running Initial Migrations

After creating the project, you have to create some basic tables such as User, Session, and others, to provide the default behaviors of Django.

(venv)$ cd buyandsell
(venv)$ python migrate

Create a Superuser

The Django super user is the equivalent of Linux root user, and this user will have all rights on the data stored on Django database. This user have all access to the admin interface.

(venv)$ cd buyandsell
(venv)$ python createsuperuser admin

Test If Your Application Is Working Correctly

Now you can test that everything is working by issuing the command inside ‘buyandsell’ root folder:

(venv)$ python runserver SERVER_IP:SERVER_PORT

Developing the Core Application

Every application we will develop in these tutorials will follow the following process:

  1. Define the database models inside the file
  2. Define the views that will handled requests inside file and we will create the template html file that will be used to render files for final users viewing
  3. Define the routes that users will follow to navigate through our applications using file.
  4. Define the admin interface configurations that will help the application administrator to effortlessly manage the entities stored on the database using file
  5. We will then customize our templates to look prettier

Initialize the Core App

(venv)$ cd buyandsell
(venv)$ django-admin startapp core

Link the Core App to the buyandsell Project

To enable Django to consider the core app as part of the buyandsell project, we have to add the following configuration to file:



Data Models

As mentioned above, this app will handle the following models:

  1. UserProfile
  2. Product
  3. ProductCategory
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from django.conf import settings
from datetime import datetime
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
photo = models.ImageField(upload_to='profile_images', blank=True)
phone = models.CharField(max_length=20)
def __str__(self):
return self.user + "profile"
def get_absolute_url(self):
return reverse("profile_detail", kwargs={"pk":})
class Product(models.Model):
""" This the default Product class """
name = models.CharField(max_length=50)
description = models.TextField(max_length=100)
photo = models.ImageField(upload_to='product_images', blank=True)
price_ht = models.FloatField()
category = models.ForeignKey("core.Category", on_delete=models.CASCADE)
created_at = models.DateTimeField(
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
TVA_AMOUNT = 19.25
def price_ttc(self):
return self.price_ht + self.TVA_AMOUNT
def __str__(self):
def get_absolute_url(self):
return reverse("product_detail", kwargs={"pk":})
class Category(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(max_length=100)
photo = models.ImageField(upload_to='category_images', blank=True)
def __str__(self):
def get_absolute_url(self):
return reverse("category_detail", kwargs={"pk":})
(venv)$ python makemigrations
(venv)$ python migrate

Views and Template Files

To enable end users to access our application from their browser, we have to define the views and the template files.

from django.shortcuts import render
from django.views.generic import DetailView, ListView, CreateView, UpdateView, DeleteView
from .models import Product, Category, UserProfile# Product views
class ProductDetailView(DetailView):
model = Product
template_name = "core/product_detail.html"
class ProductListView(ListView):
model = Product
template_name = "core/product_list.html"
class ProductCreateView(CreateView):
model = Product
template_name = "core/product_create.html"
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
class ProductUpdateView(UpdateView):
model = Product
template_name = "core/product_update.html"
class ProductDeleteView(DeleteView):
model = Product
template_name = "core/product_delete.html"
{% extends 'base.html' %}{% block title %} Creation of a product {% endblock %}{% block menu_bar %}
{{ block.super }}
<li class="active" ><a href="{% url 'product-list' %}">products</a></li>
{% endblock menu_bar %}
{% block content %}
<h3>Creation of a product</h3>
<form action="" method="post" enctype="multipart/form-data" >
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create">
<button class="button"><a href="{% url 'product-list' %}">Cancel</a></button>
{% endblock %}

Routing with URLConf

The UrlConf is the structure that defines how is navigation done on our applications. It is configured in the file

# Product Urls
urlpatterns = [
path('products/', views.ProductListView.as_view(), name='product-list'),
path('product/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'),
path('product/create/', views.ProductCreateView.as_view(), name='product-create'),
path('product/<int:pk>/update/', views.ProductUpdateView.as_view(), name='product-update'),
path('product/<int:pk>/delete/', views.ProductDeleteView.as_view(), name='product-delete'),

Admin Interface

Generally, when you build a web application to solve a business need of a client, you are also going to build an administrator application that will manage the data stored on the database, as well as access rights, permissions and roles. This is where Django simplifies the life of web developers by allowing them to not worry about this tasks because it is already done by default.

  1. You import the models you want to add in your admin application inside the file:
  • from core.models import Product
  1. You create the ModelAdmin class that will manage your own model:
  • class ProductAdmin(admin.ModelAdmin): pass
  1. You register the ModelAdmin class in the admin interface, with one of the two following methods:
  2. Using the method register of
  •, ProductAdmin)
  1. or by annotating the class ProductAdmin
  • @admin.register(Product) class ProductAdmin(admin.ModelAdmin): pass
from django.contrib import admin
from core.models import Product, Category, UserProfile
class ProductAdmin(admin.ModelAdmin):
class CategoryAdmin(admin.ModelAdmin):
class UserProfileAdmin(admin.ModelAdmin):

Styling the App with Static Files

Now that we have a working application, we are going to add some style to make it more presentable. So, we are going to use the Bootstrap 3 and Jquery libraries to add some styles to our applications.

  1. bootstrap.css
  2. bootstrap.js
  3. jquery.js
  1. Create a css folder to store css files
  2. Create a js folder to store javascript files
  3. Create images folder to store images
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
{% load static %}
{% static 'core/css/bootstrap.css' %}
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>{% block title %} Welcome to the core app !! {% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% static 'core/css/bootstrap.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'core/css/main.css' %}">
<script src="{% static 'core/js/jquery.js' %}"></script>
<script src="{% static 'core/js/bootstrap.js' %}"></script>


By the end of this tutorial, you have seen how to start building an application with the Django framework. More precisely, you have learn what a Django model, view, template is.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alibaba Cloud

Alibaba Cloud

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website: