×
Community Blog How to Develop Web Applications on Alibaba Cloud with Django Framework

How to Develop Web Applications on Alibaba Cloud with Django Framework

This tutorial shows you how you can build your application right from the cloud using the Django web framework, helping you address the challenges web developers face today.

By Bineli Manga, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

The demand in business applications is growing fast and developers are facing many challenges such as evolutivity, scalability, and re-usability. In order to satisfy business needs, developers around the world need to create new tools that will help them solve the above presented challenges.

With the development of cloud infrastructure, some of these challenges, particularly scalability and evolutivity, can be easily solved. It is now possible to do anything in the cloud, even coding with function-as-a-service (FaaS) products like Function Compute. But, to solve the re-usability problem, the solution must come from the code used for the application we are developing. This is where the Django framework comes in handy, in the way it is a useful tool to develop reusable web app and in a short time.

The purpose of this tutorial is to show you how you can build your an application right from the cloud, by using a web framework tailored to address current challenges web developers face. I hope this tutorial will help you to understand how you can build your own development environment on the cloud and benefit from the ubiquity of that solution.

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.

Okay, that's pretty straightforward, but what is a web framework? Web frameworks are reusable collections of components that handle many of the common and repetitive tasks of web-application development in an integrated fashion. Instead of requiring you to obtain disparate libraries of code and find ways to make them work together, web frameworks provide all the necessary components in a single package and take care of the integration work for you.

Great. Now that we're familiar with the concepts of web apps and frameworks, let's talk about Django. Django is one of the most recent web frameworks that is aimed at simplifying web app creation. Django gives you a set of tools that will help you quickly develop highly dynamic web applications that are re-usable, scalable and clean.

Django is built upon the DRY (Don't Repeat Yourself) paradigm, which means that in every step of the development process, you will have to write less code that the average needed using another framework.

In these series of tutorials, I'll guide you through the development of several applications and show you how the various components and applications bundled with Django can help you write less code at each stage of the development process, and how you can do all these things in the cloud. We will be running our web application on an Alibaba Cloud Elastic Compute Service (ECS) instance. I will not be covering the steps for setting up Django on your ECS. Instead you can refer to these two tutorials to learn more:

  1. https://www.alibabacloud.com/getting-started/projects/how-to-deploy-django-application-on-alibaba-cloud
  2. http://www.alibabacloud.com/blog/how-to-deploy-a-django-application-with-docker_581157

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

Install PostgreSQL database

# sudo apt-get update
# sudo apt-get install python-dev libpq-dev postgresql postgresql-contrib

Install virtualenv

# sudo pip install virtualenv

Install Pillow

This library will allow us to print profile and product images on our templates.

(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

This command will activate this virtual environment

$ 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

After successfully completing each of the steps above, the resulting project folder should look like the one presented hereafter:

buyandsell/
    buyandsell/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    db.sqlite3
    manage.py

Here are the explanations on some of the files you are seeing on that folder:

  1. settings.py: this file is used to set core configurations of our app, like database access parameters, defining static file service.
  2. urls.py: this is the file used to create URL routes from which our application will serve the content we are storing.
  3. wsgi.py: this file defines default configurations used by the web server on deployment configurations.
  4. manage.py: 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. admin.py: will be used to generate the admin interface applications.
  7. tests.py: this file defines the tests that will be ran when testing the app.
  8. app.py: 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 manage.py 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 manage.py createsuperuser admin

Note: Enter a 8 character password mixing upper and lower case letters with numbers and special characters

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 manage.py runserver SERVER_IP:SERVER_PORT

Where SERVER_IP is the public ip address of your virtual machine instance, and SERVER_PORT is the external port configured for your server.

Developing the Core Application

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

  1. Define the database models inside the models.py file
  2. Define the views that will handled requests inside views.py 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 urls.py file.
  4. Define the admin interface configurations that will help the application administrator to effortlessly manage the entities stored on the database using admin.py file
  5. We will then customize our templates to look prettier

Initialize the Core App

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

After initializing the Core app, the project folder should have a new folder with the following structure:

core/
        __init__.py
        admin.py
        apps.py
        migrations/
            __init__.py
        models.py
        tests.py
        views.py

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 settings.py file:

….
INSTALLED_APPS = [
   'core',
    …
]
….

Data Models

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

  1. UserProfile
  2. Product
  3. ProductCategory

And here is the corresponding source code:

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": self.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(default=datetime.now)
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):
return self.name        

def get_absolute_url(self):
return reverse("product_detail", kwargs={"pk": self.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):
return self.name

def get_absolute_url(self):
return reverse("category_detail", kwargs={"pk": self.pk})

After defining our models, we need to save these structures in the database, using the below commands:

(venv)$ python manage.py makemigrations
(venv)$ python manage.py 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.

We will create views and template files to manage: creation, update, delete, list and details of our models.

The content of the views.py file is shown hereafter:

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"

Here is the Html template we will use to show the product's creation form:

{% 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>
</form>
{% endblock %}

The Html template files will be placed inside the templates/core directory inside the root folder of the core application.

For more details on using Django template files, take a look at: django-website/templates

Routing with URLConf

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

Here is the content of that 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'),
]

The routes defined up here will serve as entry point to access the template files defined on the views section. The file creates a binding between a url path and the view associated with that url.

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.

In order to configure the admin interface, you have to modify the file: admin.py, and configure it to use our models.

The configuration is done in that way:

  1. You import the models you want to add in your admin application inside the admin.py file:
    from core.models import Product

  2. You create the ModelAdmin class that will manage your own model:
    class ProductAdmin(admin.ModelAdmin):
    pass

  3. You register the ModelAdmin class in the admin interface, with one of the two following methods:

    Using the method register of admin.site

    admin.site.register(Product, ProductAdmin)

    or by annotating the class ProductAdmin

    @admin.register(Product)
    class ProductAdmin(admin.ModelAdmin):
    pass


After repeating each of these steps for all of our models, we reach out with the following code for the admin.py file:
from django.contrib import admin
from core.models import Product, Category, UserProfile

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
pass

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
pass

@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
pass

After completing this, you can open your browser at the following address in order to see the admin interface:

127.0.0.1:8000/admin/

You have log in with the super user account you created earlier in this tutorial.

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.

To do so, here is the process:

Download the corresponding source files:

  1. bootstrap.css
  2. bootstrap.js
  3. jquery.js

Inside the core folder, create a sub-folder named static, and inside it, create another folder named core. We will place the static files of the core app in these folders in that way:

  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

Configure the STATIC_ROOT and STATIC_URL settings for accessing these files from the browser

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')

Integrate the static files inside the base.html file, so that any inheriting template can uses these libraries

First, we load all the static libraries, using from template tag: load static

{% load static %}

Now we can use any static resource contained inside the static folder using this tag, as follow:

{% static 'core/css/bootstrap.css' %}

Here is the resulting base.html file with all our static resources correctly imported.

<!DOCTYPE html>
<html lang="en">
<head>
<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' %}">

</head>

<body>
<script src="{% static 'core/js/jquery.js' %}"></script>
<script src="{% static 'core/js/bootstrap.js' %}"></script>
</body>
</html>

Conclusions

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.

The source code of the application used for this tutorial can be found here on GitHub:

https://github.com/binel01/buyandsell/tree/master/core

0 0 0
Share on

Alibaba Clouder

1,039 posts | 162 followers

You may also like

Comments

Alibaba Clouder

1,039 posts | 162 followers

Related Products