Introduction to django and environment-setup

Course Objectives

  • Understand the features and advantages of the Django framework
  • Master how to build a Django development environment
  • Learn to create and run django projects

What is django?

Django is an advanced Python web framework that encourages rapid development and clean, practical design - without you having to write login verification, form verification and other common functions from scratch, the amount of code can be cut by more than half.

It follows the MVT (Model-View-Template) architecture pattern (which will be dismantled in detail in the next lesson), just like building blocks: data, logic, and interfaces each perform their own duties; it also has a bunch of built-in functions that can be used out of the box, such as **'s own management background, ORM database interaction, session management, security protection, etc., which can help you quickly build a website that is safe, reliable, and easy to maintain later.

The main features of django

Just talk without practicing the tricks? Let’s first list a few core selling points that both novices and enterprises love to use👇

  • Rapid development without duplication: Adhering to the "fast and efficient development concept", some people even joked that "using Django can write someone else's project framework for a month in one week"
  • Reliable security protection: Automatically help you avoid SQL injection, XSS cross-site scripting, CSRF cross-site request forgery, these security pitfalls that novices/veterans often step on
  • Effortless from small to large use: From personal to-do lists, technology blogs, to 100 million user-level applications such as Douban and Instagram, it can be easily adapted
  • Multiple languages ​​and multiple regions can be changed at will: Built-in complete internationalization system. Do you want to make a website in Chinese, English and Japanese versions? Just have a dictionary

Environment preparation

If you want to do your job well, you must first sharpen your tools and set up a good development environment!

System requirements

Django currently only supports Python 3.8 and above, and you need to ensure that your computer has the pip package management tool that comes with Python (or has been upgraded separately) - this is a necessary tool for Python to download and install third-party libraries.

How to check whether Python and pip are installed? Open a terminal (PowerShell/CMD for Windows, Terminal for Mac/Linux) and enter the following command👇

# 检查Python版本
python --version
# 如果上面的命令在Mac/Linux报错,或者Windows没反应,试试python3 --version

# 检查pip版本
pip --version
# 同样,有问题就试pip3 --version

If the version meets the requirements, you can continue; if it is not installed or the version is too low, first go to Python官网 to download and install the latest stable version of Python (remember to check "Add Python X.X to PATH" when installing)


Install django

After the environment check is OK, just use pip to install it - Django official will update the stable version regularly, just execute the following command👇

# 国内小伙伴可以加上国内镜像源,速度更快!
pip install django -i https://pypi.tuna.tsinghua.edu.cn/simple

Verify installation

After the installation is complete, verify whether django is successfully installed and whether the version is correct👇

python -m django --version

If the terminal outputs a string of numbers like "5.1.x" and "4.2.x", it means the environment is set up! Django's long-term support version (LTS) is generally supported for 3 years. Newbies are recommended to install the LTS version for more stability, such as the current 4.2 or 5.1 (which may be updated later)


Create django project

Next, we use the command line tool django-admin officially provided by Django to create a new project skeleton, let’s call it “mysite” ~

Step 1: Enter the working directory

First cd in the terminal to the folder where you want to store the project, for example, I want to put it in the Projects folder in "Documents"👇

# Windows PowerShell/CMD示例
cd C:\Users\你的用户名\Documents\Projects
# Mac/Linux示例
cd ~/Documents/Projects

Step 2: Create a project

After entering the working directory, execute the create command👇

django-admin startproject mysite

Step 3: See what is generated?

After executing the above command, there will be an additional folder called "mysite" in your Projects folder. We can use the tree command or manually open it to see the structure👇

mysite/
    manage.py          # django项目的「万能工具箱」
    mysite/
        __init__.py    # 空文件,用来告诉Python「这是一个Python包」
        settings.py    # 项目的「全局配置中心」
        urls.py        # 项目的「URL路由地图」
        wsgi.py        # WSGI兼容的Web服务器入口(生产环境用)
        asgi.py        # ASGI兼容的Web服务器入口(支持异步、实时通讯用)

A brief explanation of several core files:

  1. manage.py: Don’t worry about its internal code, just know that it is the main tool for you to interact with the Django project - the subsequent creation of applications, starting the development server, and database migration all rely on it
  2. settings.py: We will often change this file later - time zone, language, installed applications, and database configuration are all here
  3. urls.py: Tell django "which function/view will be called when the user visits the URL"

Run the development server

The project skeleton is set up, let's start the lightweight development server that comes with Django and see the effect~ This server is only used during development and debugging, never use it in the production environment!

Step 1: Enter the project root directory

Terminal continues execution👇

cd mysite

Step 2: Start the server

Execute startup command👇

python manage.py runserver

Step 3: Visit the website

Open your browser and visit the address displayed on the terminal (usually http://127.0.0.1:8000/ or http://localhost:8000/)

If you see a welcome page with a rocket pattern that says "The install worked successfully! Congratulations!" (or "The installation worked successfully! Congratulations!" in Chinese - it will be in Chinese when we change the configuration later), it means that the project is running! 🎉

Tips: Customize port number

If you want to change the port number to start the server, such as changing it to 8080, just add the port number after the command👇

python manage.py runserver 8080

django project configuration

The welcome page just now is in English by default. Let’s change a few commonly used configurations to make it more in line with our development habits!

Find the "Global Configuration Center" mentioned just nowmysite/mysite/settings.py, open it with your favorite editor (such as VS Code, PyCharm)

Main configuration item modifications

Let’s change a few of the most commonly used ones👇

1. Language and time zone configuration

Change the default English to Chinese and the default UTC time zone to Shanghai, China👇

# 国际化配置
LANGUAGE_CODE = 'zh-hans'  # 改成中文简体
USE_I18N = True            # 开启国际化支持
USE_TZ = True             # 开启时区支持

# 时区配置
TIME_ZONE = 'Asia/Shanghai'  # 改成中国上海时区

After making the changes, refresh the browser’s welcome page and it will become Chinese!

2. Database configuration

Django uses SQLite3 as the default database by default - SQLite3 is a lightweight file database that does not require a separate server installation and is suitable for development and debugging. If the production environment has a large amount of data, it can be replaced by MySQL, PostgreSQL, etc.

# 数据库配置(默认不用改,开发够用啦!)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

Introduction to management commands

We just useddjango-admin startprojectandpython manage.py runserver, let me introduce to you a few that will be frequently used in the future.manage.pyManagement commands**👇

# 1. 创建一个新的应用(比如叫blog)
# django项目是由多个应用组成的,比如一个电商网站可能有用户应用、商品应用、订单应用
python manage.py startapp blog

# 2. 数据库迁移(后面讲MTV的Model层会详细讲)
# 第一步:生成迁移文件(记录你对Model层的修改)
python manage.py makemigrations
# 第二步:执行迁移文件(把修改应用到数据库)
python manage.py migrate

# 3. 创建超级用户(用来登录django自带的管理后台)
python manage.py createsuperuser

# 4. 收集静态文件(生产环境部署用)
python manage.py collectstatic

Course Summary

In this lesson we learned:

  1. What is django and what are its core features and advantages?
  2. How to check and set up the django development environment (Python+pip+django)
  3. How to usedjango-adminCreate a django project
  4. How to usemanage.pyStart the development server
  5. How to modify the common configuration of the project (language, time zone)
  6. Several commonly used onesmanage.pyAdministrative commands

In the next lesson, we will have an in-depth understanding of Django's MVT architecture pattern and see what Model, View, and Template do respectively, and how they cooperate with each other!