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.
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
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.
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
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
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
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
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
(venv)$ cd venv
(venv)$ pip install django==2.1
(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.
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
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.
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.
All applications developed in this tutorial follow the process below.
(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
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',
…
]
….
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
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
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.
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.
from core.models import Product
class ProductAdmin(admin.ModelAdmin):
pass
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.
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.
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>
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