Use Django to develop a blog website and deploy it online using Nginx + Gunicorn on Alibaba Cloud (Development)

In this article, we will implement a simple personal blog website through Django+Mysql, and implement online deployment and operation of the website through Nginx and gunicorn on Alibaba Cloud.

In order to quickly implement the system, we only completed the functional pages of blog post list and blog post details. To maintain related data, we directly call the Admin management background that comes with Django to update the database information.

Table of contents

Development environment preparation

Configure virtual environment

Install Django

Create a Django project

Database creation and connection configuration

Database creation

Django database connection configuration

Blog website function module development

Create App

Register APP

Define model

Data migrations

Define view functions

Configure access route URL

Static resource preparation and configuration

Front-end web template creation

Django background enable configuration

test run

Conclusion


 Development environment preparation

The development-related environments and software versions used in this article are as follows:

Server: Python 3.9

Web framework: Django 4.10

Database: MySQL mysql-8.0.13-winx64

Development tool IDE: Pycharm (Community Edition)

Front-end framework: Bootstrap 5

This article will not give a special introduction to the installation of Python, Mysql, and Pycharm. Students in need please refer to the following blog post.

Python + Django4 to build a personal blog (2): Prepare the development environment_Li Weiweiwiwi's blog-CSDN blog The development-related technologies and software versions used in this series of blog posts to implement the blog website are as follows: Server: Python 3.9 Web framework: Django 4.10 Database: MySQL mysql-8.0.13-winx64 development tool IDE: Pycharm (community edition) front-end framework: Bootstrap 5 https://blog.csdn.net/agelee/article/details/126406215

Configure virtual environment

Project development based on Python is currently basically developed in an independent virtual environment. This can make each project environment independent from other projects, keep the environment clean, and solve package conflicts.

So our first step in Python development is to configure the virtual environment.

Starting from Python version 3.3, it comes with a virtual environment. It does not need to be installed, just configure it and you can use it.

Create a new folder on any disk, as shown in this article E:\django_project.

Open this folder with Pycharm:

Enter the command to configure venv in the Terminal input box of Pycharm, where env is the directory where the virtual environment is placed:

python -m venv env

After the creation is completed, enter the following env\Scripts\activate.batto enter the virtual environment:

There is an (env) mark before the drive letter , indicating that the entry into venv is successful.

Install Django

After the virtual environment is created, we can install django. This article is based on django4.1. Enter the following command in the Terminal input box of Pycharm pip install django==4.1to start installing Django.

Here I django==4.1have specified the django version as 4.1. If the version is not specified, pip install djangothe latest version will be installed directly.

After the installation is complete, enter Python (you can enter the Python editor through the command line or in Pycharm) and enter the following command to check whether the installation is successful.

import django

django.get_version()

If the Django version information appears, the installation is successful.

Create a Django project

Enter the command to create a Django project through Pycharm's Windows command line input interface django-admin startproject django4blogto create a new project: django4blog

After the project is created, we will see the automatically generated project folder E:\django_projectin the Pycharm folder.django4blog

cd django4blogGo to the project folder

Then we test whether our django project is created successfully and enter the django command in the terminal input box:python manage.py runserver

Open the default server port address in the browser: http://127.0.0.1:8000/ . If the following page appears, it means that we have successfully created and run a Django project.

Database creation and connection configuration

Django provides good support for various databases, including: PostgreSQL, MySQL, SQLite, and Oracle.

Django provides a unified calling API for these databases.

We can choose different databases according to our business needs.

MySQL is the most commonly used database in web applications.

This article uses MySQL.

This step connects the database settings to your own MySQL database and completes the creation of the database.

Database creation

Django can only operate at the data table level and cannot operate at the database level, so you need to create a database manually: blog

We can create a database via the command line:

1. Enter the bin subfolder directory of the mysql installation folder:

for example:D:\Program Files\mysql-8.0.13-winx64\bin

2. Connect to the database:

mysql -u root -p Enter password:******

3. After successful connection and login, create a database through the command: django_blog

CREATE DATABASE IF NOT EXISTS django_blog DEFAULT CHARSET utf8;

Django database connection configuration

Django requires the mysql driver to use MySQL. If you have not installed the mysql driver, you can execute the following command to install it:

pip install pymysql

After installation, enter the folder django4blogunder the project , open the settings.py file, find the DATABASES configuration item, and modify the DATABSES configuration item as follows:django4blog

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',    # 数据库引擎
        'NAME': 'django_blog', # 数据库名称
        'HOST': '127.0.0.1', # 数据库地址,本机 ip 地址 127.0.0.1
        'PORT': 3306, # 端口
        'USER': 'root',  # 数据库用户名
        'PASSWORD': '123456', # 数据库密码
    }
}

Then use the pymysql module to connect to the mysql database:

Introduce the module and configure it in __init__.py in the same directory as settings.py:

import pymysql
pymysql.install_as_MySQLdb()

At this point, we have created a Django project django4blog for programming our subsequent online exam management system development.

At the same time, a MySQL database was created for this project: blogused for data storage and processing during our program development process.

Blog website function module development

After a Django project framework is built, all our program development for the front and backend of the system can be carried out in this project. The development of a typical Django project module function includes the following steps:

  • create app
  • Register app
  • Define model
  • Define view functions
  • Configure access route URL
  • Static resource preparation and configuration
  • Front-end web template development
  • Test and run

Create App

An app in Django represents a functional module, and Django's specific data model and functional view implementation are based on the app.

Here, we first create a file articlecalled appto manage our blog posts.

Enter the command in Terminal:python manage.py startapp article

Check the directory and you will find that a new folder articlenamedapp

Register APP

Next we need to "tell" Django that there is now an app like article.

Open settings.py in the django4blog directory, find INSTALLED_APPS and write the following code:

# Application definition
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 新增'article'代码,激活app
    'article',
]

Define model

Django uses models to map fields in the program to the database, and to pass data between the program and the data.

Django models use the built-in ORM.

Object Relational Mapping (ORM for short) is used to convert data between different types of systems in object-oriented programming languages.

We created a blank database before blog, and in this step we use Django's model to create the database table.

Because Django has its own mapping rules between the model and the target database, if you create a data table in the database yourself, it may not necessarily comply with Django's table creation rules, resulting in the inability to establish communication between the model and the target database.

So it is best for us to create the corresponding database table through the Django model in the Django project.

Open it django4blog/article/models.pyand add the following code:

from django.db import models
# timezone 用于处理时间相关事务。
from django.utils import timezone


# Create your models here.
# 博客文章数据模型
class Article(models.Model):
    # 文章id,主键
    id = models.AutoField(primary_key=True)
    
    # 文章作者 ,用于指定数据删除的方式
    author = models.CharField(max_length=100)
    
    # 文章标题,models.CharField 为字符串字段,用于保存较短的字符串,比如标题
    title = models.CharField(max_length=100)
    
    # 文章正文,保存大量文本使用 TextField
    body = models.TextField()
    
    # 文章创建时间,参数 default=timezone.now 指定其在创建数据时将默认写入当前的时间
    created = models.DateTimeField(default=timezone.now)
    
    # 文章更新时间,参数 auto_now=True 指定每次数据更新时自动写入当前时间
    updated = models.DateTimeField(auto_now=True)

Data migrations

After completing the definition of the model, create the corresponding data table in the target database. This step is called data migration in Django.

Note that whenever a change (addition, modification, deletion, etc.) is made to the database, data migration is required.

Creating a data table in the target database requires executing two instructions, namely the makemigrations and migrate instructions.

python manage.py makemigrations

python manage.py migrate

Define view functions

In this step, we implement a simple function to obtain the blog post information from the database and pass it to the front-end web page.

from django.shortcuts import render

# 导入数据模型Article
from .models import Article

def article_list(request):
    # 取出所有博客文章
    articles = Article.objects.all()
    # 需要传递给模板(templates)的对象
    context = { 'articles': articles }
    # render函数:载入模板,并返回context对象
    return render(request, 'article/list.html', context)

Configure access route URL

After having the view, we need to map the view function to the front-end web page link.

The url can be understood as the URL link entered when accessing the website. After configuring the url, Django knows how to locate the app and use the corresponding view function to obtain background data.

In this article, we add two links to obtain the article list and article details respectively.

Open django4blog/urls.py and enter the following code:

from django.contrib import admin
from django.urls import path, re_path
# 引入app视图
from django4blog import article

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^$', article.views.article_list),
    path('list/', article.views.article_list, name='list'),  # 文章列表
    path('detail/<int:id>/', article.views.article_detail, name='detail'),  # 文章详情
]

Static resource preparation and configuration

The front-end and back-end of this system are not separated. The front-end framework uses the currently popular Bootstrap5. In order to develop quickly, all pages of this system are developed using native Bootstrap and no third-party templates and themes are used.

Download Bootstrap · Bootstrap v5 Chinese Documentation v5.1 | Bootstrap Chinese website Download Bootstrap to get compiled CSS and JavaScript files, source code, or add Bootstrap to you through your favorite package manager, such as npm, RubyGems, etc. in the project. https://v5.bootcss.com/docs/getting-started/download/

Create a new folder static in the project root directory to store front-end template static resources.

Copy the css and js folders just extracted by Bootstrap to the static folder.

After completion, the Static folder structure is as follows:

After preparing the static resources, we also need to specify the storage location of the static files in Django so that they can be correctly referenced in the template.

Configure the following in django4blog/settings.py:

import os

STATIC_URL = '/static/'
 
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),  # 添加此项

Front-end web template creation

Template inclusion is the content in Django that is ultimately displayed in the browser. It is actually an html web page file that contains some Django template engine syntax.

Before creating a template, we first create a new folder templates in the root directory to store all our template files.

The template location also needs to be configured to specify the storage location of the template. Configure the following in django4blog/settings.py:

Then we create three new files in the template file:

  • base.html: is the template base of the entire project, and all web pages inherit from it;
  • header.html: is the navigation bar at the top of the web page;
  • footer.html: It is the footnote at the bottom of the web page.

Write the codes for three static HTML files respectively as follows:

templates/base.html:

<!--    载入静态文件-->
{% load static %}

<!DOCTYPE html>
<!-- 网站主语言 -->
<html lang="zh-cn">
<head>
    <!-- 网站采用的字符编码 -->
    <meta charset="utf-8">
    <!-- 预留网站标题的位置 -->
    <title>{% block title %}{% endblock %}</title>
    <!-- 引入bootstrap的css文件  -->
    <link type="text/css" rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
    <!-- 引入图标库 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
</head>

<body>
<!-- 引入导航栏 -->
{% include 'header.html' %}
<!-- 预留具体页面的位置 -->
{% block content %}{% endblock content %}
<!-- 引入注脚 -->
{% include 'footer.html' %}
<!-- bootstrap.js 依赖 jquery.js 和popper.js,因此在这里引入 -->

<!--
    popper.js 采用 cdn 远程引入,意思是你不需要把它下载到本地。
    在实际的开发中推荐静态文件尽量都使用 cdn 的形式。
    教程采用本地引入是为了让读者了解静态文件本地部署的流程。
-->
{#<script src="https://unpkg.com/@popperjs/core@2"></script>#}

<!-- 引入bootstrap的js文件 -->
<script type="text/javascript" src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
</body>

</html>

templates/header.html:

<!-- 定义导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container">

        <!-- 导航栏商标 -->
        <a class="navbar-brand" href="#">我的博客</a>

        <!-- 导航入口 -->
        <div>
            <ul class="navbar-nav">
                <li class="nav-item">
                    <!-- 改写了这里的 href -->
                    <a class="nav-link" href="{% url 'list' %}">首页</a>
                    {#          <a class="nav-link" href="/list">首页</a>#}
                </li>
            </ul>
        </div>

    </div>
</nav>

templates/footer.html:

{% load static %}
<!-- Footer-->
<div>
    <br><br><br>
</div>
<footer class="py-3 bg-light fixed-bottom">
    <div class="container">
        <p class="m-0 text-center text-black-50">Copyright &copy; django4blog</p>
    </div>
</footer>

The above three files are common component modules of website pages. Basically, each page will not change, so we separate them.

When we write Django's subsequent page templates, we can directly inherit the corresponding common template components.

In the templates folder, we first create a new article folder to manage article-related templates.

Next, we write template pages corresponding to the article list and article details view based on three common components:

django4blog/templates/article/list.html:

<!-- extends表明此页面继承自 base.html 文件 -->
{% extends "base.html" %}
{% load static %}

<!-- 写入 base.html 中定义的 title -->
{% block title %}
    首页
{% endblock title %}

<!-- 写入 base.html 中定义的 content -->
{% block content %}
<!-- 定义放置文章标题的div容器 -->
 <br>
<div class="container">
    {% for article in articles %}
    <div class="row mt-2">
        <!-- 文章内容 -->
        <div class="col-sm-12">
            <!-- 卡片容器 -->
            <div class="card h-100">
                <!-- 标题 -->
<!--                <h4 class="card-header">{
   
   { article.title }}</h4>-->
                <!-- 摘要 -->
                <div class="card-body">
                    <h4 class="card-title">{
   
   { article.title }}</h4>
                    <br>
                    <p class="card-text">{
   
   { article.body|slice:'100' }}...</p>
                    <a href="{% url 'detail' article.id %}"  class="card-link">阅读本文</a>
                </div>
            </div>
        </div>
    </div>
    {% endfor %}
    <br>
</div>
{% endblock content %}

django4blog/templates/article/detail.html :

<!-- extends表明此页面继承自 base.html 文件 -->
{% extends "base.html" %}
{% load static %}

<!-- 写入 base.html 中定义的 title -->
{% block title %}
    文章详情
{% endblock title %}

<!-- 写入 base.html 中定义的 content -->
{% block content %}

    <!-- 文章详情 -->
    <div class="container">
        <!--    <div class="row">-->
        <!-- 标题及作者 -->
        <h1 class="col-12 mt-4 mb-4">{
   
   { article.title }}</h1>
        <div class="col-12 alert alert-primary">
            <div class="col-12">
                <a>作者:{
   
   { article.author }}</a>
                &nbsp
                <a>{
   
   { article.created|date:'Y-m-d H:i:s' }}</a>
            </div>
        </div>
        <!-- 文章正文 -->
        <div class="col-12">
            <p>{
   
   { article.body }}</p>
        </div>
        <!--    </div>-->

{% endblock content %}

Django background enable configuration

Django comes with its own background function. We can use the background function to directly update our background data table information in just two steps.

1. Create a super user

Enter at the command line:python manage.py createsuperuser

After entering the user name, email and password according to the prompt information, the system will create a super user.

2. Register the model to admin

Open django4blog/article/admin.py and enter the following code to register all models in the admin. Then we can update our data table in the background of Django.

from django.contrib import admin

# Register your models here.
from .models import Article

# 注册Article到admin中
admin.site.register(Article)

test run

At this point, our Django part of the development work is basically completed.

Enter the command in the terminal: python manage.py runserverstart the server.

Enter the backend URL http://127.0.0.1:8000/admin and log in:

Add a record:

Return to the list page http://127.0.0.1:8000/ :

Clicking the button to read this article will open the URL: http://127.0.0.1:8000/detail/1/

Conclusion

In this article, we use the Python + Django framework to complete a simple blog website, realizing the two core functions of blog post list and blog post details.

While writing the code, I found that there is actually a lot of content in the subsequent deployment, so I decided to divide the blog post into two parts. In the next part, we will learn how to apply for an Alibaba Cloud server and how to connect and manage the data and configuration of the Alibaba Cloud server on Windows. .

Finally achieve the ultimate goal of deploying this blog website online.

Guess you like

Origin blog.csdn.net/agelee/article/details/127425833