How to build an application from the cloud using the Django web framework

This article will show you how to build applications from the cloud using the ** Django web framework ** to help web developers address the challenges they face today.

Why Django?

Before we talk about Django, let's talk about what a web application is. A web application is a collection of code written in a programming language that is rendered on a browser and usually addresses well-defined problems. For example, a blog post (like this one!), An e-commerce website, or a social network.

Well, this is pretty easy, but what is a web framework? A web framework is a collection of reusable components that handle many of the common and repetitive tasks of web application development in an integrated way. Instead of having to get libraries of different code and find a way to get them to work together, the web framework provides all the components you need in a single package and takes care of the integration. ..

Now that you know the concept of web apps and frameworks, let's talk about Django. Django is one of the latest web frameworks aimed at simplifying the creation of web apps. Django provides a set of tools to help you quickly develop reusable, scalable, clean, and highly dynamic web applications.

Django builds on the DRY (Don't Repeat Yourself) paradigm, and you have to write less code than the average code required using other frameworks at every step of the development process. It means not to be.

This series of tutorials will guide you through the development of several applications, how the various components and applications bundled with Django can help you write less code at each stage of the development process. Here's how to do all this in the cloud. This time, run the web application on an Alibaba Cloud Elastic Compute Service (ECS) instance. It doesn't explain how to set up Django on ECS. Instead, refer to the following two tutorials.

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

Project definition

The project we are trying to build is an e-commerce web application that allows people to buy and sell goods. For flexibility and maintainability, the project is divided into three independent apps: core app, cart app, and payment app.

Presentation of each application

Core application

As mentioned earlier, the core app manages everything (additions, changes, deletions) related to the product you want to sell. The core app aims to manage the entire purchasing process.

1, user (buyer / seller and administrator) 2, product information 3, product category

Cart application

The cart application is used to manage the buying and selling process. The specific elements managed here are as follows.

1, purchase and sale options 2, client's cart and cart items 3, Add / Remove Items to Cart

Payment application

The payment app gives you access to the payment gateway and allows you to receive the money passed by the client. Click here for details:

1, payment gateway 2, payment method 3, payment API integration

Development environment settings

Install python 3 and pip

$ python --version
# sudo apt-get install python3
# sudo apt-get install python-pip

PostgreSQL database installation

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

Install virtualenv

# sudo pip install virtualenv

Pillow installation By using this library, you will be able to print profiles and product images on templates.

(venv)$ pip install pillow

Project launch and configuration

Create and activate a virtual environment

This command creates a virtual environment in the venv folder that defaults to python3 as the python interpreter.

$ virtualenv venv --python=python3               
$ cd venv

This command activates this virtual environment.

$ source bin/activate      

Install Django in a virtual environment

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

Create a Django project

(venv)$ django-admin startproject buyandsell

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

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

Here are some of the files displayed in that folder.

1, ** settings.py **: This file is used to set the core configuration of the app, such as database access parameters, static file service definitions, etc. 2, ** urls.py **: This file is used to create a URL root that provides the content stored by the application. 3, ** wsgi.py **: This file defines the default settings used by the web server in the deployment settings. 4, ** manage.py **: The main script for managing Django projects and their applications (database migration, test execution, development server execution). 5, ** db.sqlite3 **: This is Django's pre-configured default database. Use it for development only, but when deploying, change it to a PostgreSQL database that will be used in conjunction with your Django application. 6, ** admin.py **: Used to generate an admin interface application. 7, ** tests.py **: Define the tests to run when testing your app. 8, ** app.py **: This file contains the default settings for your app.

Perform an initial migration to initialize the database

After you create your project, you must create basic tables such as User, Session, etc. to provide Django's default behavior.

(venv)$ cd buyandsell
(venv)$ python manage.py migrate

Create superuser

The Django superuser is the root user of Linux, and this user has all rights to the data stored in the Django database. This user has all access to the admin interface.

(venv)$ cd buyandsell
(venv)$ python manage.py createsuperuser admin

Note: Enter an 8-character password that is a mixture of uppercase and lowercase letters and special characters.

Test if the application is working properly

You can test that it is working by issuing a command in the'buyandsell'root folder.

(venv)$ python manage.py runserver SERVER_IP:SERVER_PORT

SERVER_IP is the public IP address of the virtual machine instance and SERVER_PORT is the external port configured on the server.

Core application development

All applications developed in this tutorial follow the process below.

  1. Define the database model in the models.py file.
  2. Define the views that handle the request in the views.py file and create a template HTML file that will be used to render the file for the final user to view.
  3. Use the urls.py file to define a route for the user to navigate the application.
  4. Use the admin.py file to define administrator interface settings that help application administrators effortlessly manage the entities stored in the database. 5, then customize the template to make it look more cute.

Initialization of 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 your core app to a buyandsell project

In order for Django to consider the core app as part of the buyandsell project, you need to add the following settings to your settings.py file:

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

Data model

As mentioned above, this app handles the following models.

1, user profile 2, product 3, product category 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 the model, you need to save these structures in the database using the following command:

(venv)$ python manage.py makemigrations
(venv)$ python manage.py migrate

Views and template files

You need to define views and template files so that your end users can access your application from your browser.

Create views and template files to manage model creation, updates, deletions, lists, and details.

The contents of the views.py file are shown below.

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, we will introduce the Html template used to display the product 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 file is located in the templates / core directory inside the core application's root folder.

For more information on using Django template files, see: django-website / templates

Routing by URLConf

UrlConf is a structure that defines how navigation is done on your application. It is set in the file views.py.

Below is the contents 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 so far serve as entry points for accessing the template files defined in the view section. This file creates a binding between the URL path and the view associated with that URL.

Administrator interface

In general, when you build a web application to solve your client's business needs, you also build an administrator application that manages the data, permissions, permissions, and roles stored in the database. Django simplifies the life of web developers because this is already done by default.

To configure the admin interface, you must modify admin.py and configure it to use the model.

The settings are made in this way.

  1. Import the model you want to add to the admin application in the admin.py file.
from core.models import Product
  1. Create a ModelAdmin class that manages your model.
class ProductAdmin(admin.ModelAdmin):
pass
  1. Register the ModelAdmin class of the admin interface using one of the following two methods: Use the register method of admin.site
admin.site.register(Product, ProductAdmin)

Alternatively, annotate class ProductAdmin.

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

After repeating these steps for all models, use the following code in 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

Once this is done, you can open your browser at the following address to see the admin screen.

127.0.0.1:8000/admin/

You logged in with the superuser account created in this tutorial.

App styling with static files

Now that we have a working application, we are trying to add some styles to make it more visible. So use Bootstrap 3 and the Jquery library to add styles to your application.

There is a process to do this.

Download the corresponding source file.

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

Create a subfolder called static inside the core folder, and create another folder named core inside it. In this way, place the core app static files in these folders.

  1. Create a css folder to store the css file
  2. Create a js folder to save the javascript file 3, create an image folder to save images

Set STATIC_ROOT and STATIC_URL settings to access these files from your browser

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

Consolidate static files into the base.html file and make inherited templates available to these libraries.

First, load all static libraries.

{% load static %}

You can now use this tag to use static resources in a static folder, as shown below.

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

Below is the base.html file that results from the successful import of all static resources.

<!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>

Conclusion

By the end of this tutorial, you'll see how to build your application using the Django web framework. More precisely, you've learned what Django's models, views, and templates are.

The source code for the application used in this tutorial can be found on GitHub.

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

Recommended Posts

How to build an application from the cloud using the Django web framework
Try using the Python web framework Django (1)-From installation to server startup
Try using the web application framework Flask
How to create an article from the command line
(Python) Try to develop a web application using Django
How to deploy a Django application on Alibaba Cloud
[Learning memo] How to make an application with Django ~ From virtual environment to pushing to github ~
How to write custom validations in the Django REST Framework
Try using the Python web framework Django (2) --Look at setting.py
How to reset password via API using Django rest framework
How to generate a query using the IN operator in Django
How to do the initial setup from Django project creation
How to hit NAPALM from the Web (NetDevOpsSec reality solution)
WEB application development using Django [Application addition]
Build a web application with Django
Development of WEB application using Django [Add data from management screen]
How to get followers and followers from python using the Mastodon API
How to deploy a web application on Alibaba Cloud as a freelancer
WEB application development using Django [Model definition]
How to check the version of Django
WEB application development using Django [Request processing]
WEB application development using Django [Template addition]
How to operate Linux from the console
Create an application using the Spotify API
How to access the Datastore from the outside
I want to operate DB using Django's ORM from an external application
How to pass values to JavaScript variables directly from the [Django] template tag
How to fix the shit heavy when reading Google Cloud Storage images from Django deployed on GAE
Try to write code from 1 using the machine learning framework chainer (mnist edition)
Let's make an A to B conversion web application with Flask! From scratch ...
How to open a web browser from python
How to build an environment for using multiple versions of Python on Mac
WEB application development using Django [Admin screen creation]
An example of cloudbuild.yaml when auto-deploying Django to App Engine with Cloud Build
How to call Cloud API from GCP Cloud Functions
Try using the Python web framework Tornado Part 1
How to automatically generate API document with Django REST framework & POST from document screen
How to print debug messages to the Django console
How to use the Google Cloud Translation API
How to operate Linux from the outside Procedure
How to measure line speed from the terminal
Try using the Python web framework Tornado Part 2
Beginners try to make an online battle Othello web application with Django + React + Bootstrap (1)
[Learning memo] How to make an application with Django ~ Until Hello World is displayed ~
[Cloud9] Try to build an environment with django 1.11 of Python 3.4 without understanding even 1 mm
[Python] How to remove duplicate values from the list
The wall of changing the Django service from Python 2.7 to Python 3
How to write a GUI using the maya command
Steps from installing Django to displaying an html page
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
Send log data from the server to Splunk Cloud
How to use Azure Table storage from Django (PTVS)
Backtrader How to import an indicator from another file
How to build a Django (python) environment on docker
How to instantly launch Jupyter Notebook from the terminal
How to deploy a Go application to an ECS instance
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
[Introduction to Udemy Python3 + Application] 30. How to use the set
[Introduction to Python] How to stop the loop using break?
How to post a ticket from the Shogun API