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.
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:
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.
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:
The cart application will be used to manage the buying and selling process. The specific elements that will be managed here will be:
The payment app will give the access to payment gateways, allowing to receive the money given by the clients. It includes:
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
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
(venv)$ cd venv
(venv)$ pip install django==2.1
(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:
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
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
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.
Every application we will develop in these tutorials will follow the following process:
(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
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',
…
]
….
As mentioned above, this app will handle the following models:
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
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
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.
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:
from core.models import Product
class ProductAdmin(admin.ModelAdmin):
pass
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
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.
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:
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:
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>
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:
Bootstrapping Function Compute for Web Using NodeJS SDK: Part 2
Building Very Fast App Backends with Falcon Web Framework on PyPy
2,599 posts | 762 followers
FollowAlibaba Cloud Community - January 10, 2022
Alibaba Clouder - April 15, 2019
Alibaba Clouder - August 26, 2020
Alibaba Clouder - April 28, 2021
Alex - August 26, 2019
Alibaba Clouder - December 17, 2018
2,599 posts | 762 followers
FollowElastic and secure virtual cloud servers to cater all your cloud hosting needs.
Learn MoreCloud-based and lightweight servers that are easy to set up and manage
Learn MoreAlibaba Cloud Function Compute is a fully-managed event-driven compute service. It allows you to focus on writing and uploading code without the need to manage infrastructure such as servers.
Learn MoreMore Posts by Alibaba Clouder