python web development - getting started with Django

Opening chapter

Through the previous article python entry practice - student management system I practiced a bunch of python syntax. This article summarizes the introduction of Django as a web framework. The premise is to have relevant web development experience (Java, php, etc.). Because this article will not involve the concept of http protocol, separation of front and back end.


  1. Official course:
  2. Rookie tutorial:


My development environment

  • Operating system: MacOS
  • IDE: vscode
  • Database: mysql
  • python version 3.x


  1. Install django (for non maOS operating system, please refer to the opening tutorial to choose the installation method and verify whether the installation is successful)

     python3 -m pip install django==1.11.6
  2. Create project

     Django admin startproject HelloWorld (this is the project name)

Four places are marked in the picture
 1. After creating the helloworld project, you will find that there is another helloworld under helloworld. The helloworld mentioned later is generally the first level, which is referred to as the project root directory
 2. is mainly for some configurations, such as database, static file storage location, etc
 3. mainly configures the mapping relationship between URLs and functions
 4. provides commands for managing projects, such as starting projects. Please pay more attention later
  1. Enter project root

    cd helloworld
  2. Launch the project and access

(it will fail to start here because of the compatibility between python3 and django. Anyway, there is a problem in the django version I use. The solution is to delete a comma of a file. If I meet it, Baidu will find out. The specific content was forgotten to save at the beginning.)

    python3 runserver
    // You can also specify ip: host
    python3 runserver localhost:8080

  1. So far, a web project prototype has been developed

Continue to improve

At this point, we can develop our own web applications, but you may also ask

  1. Where is the function called by http request written and how is the mapping relationship between function and page reflected
  2. Location of static files

Let's talk about the new helloword project

Function and its mapping

Find a file under helloworld/helloworld /

Default configuration:

    from django.conf.urls import url
    from django.contrib import admin
    urlpatterns = [

After amendment:

    from django.conf.urls import url

    from django.contrib import admin

    # Here's what's new
    from django.shortcuts import HttpResponse, render, redirect

    # 1. Jump page
    # render means that visiting http://localhost:8000/index will jump to the index.html page
    def index(request):
        return render(request, 'index.html')

    # 2. Jump to the page with parameters
    def index02(request):
        return render(request, 'index.html', {'Parameter name', value})
    # 3. redirection
    def index03(request):
        return redirect('/index/')
    # 4. Receiving parameters
    def index04(request):
        # Receive post request parameters
        request.POST.get('Parameter name')
        # Receive get request parameters
        request.GET.get('Parameter name')
        return render(request, 'index.html')     
    # Configure url mapping
    urlpatterns = [
        # Configure url mapping
        # Visit http://localhost:8000/index / and the above index function will be called
        url(r'^index/', index), 
        # TODO omits index02, index03, index 04 mapping configuration
  1. Static file storage location

Find helloworld/helloworld / there is a file below

html file configuration: about more than 50 lines

    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    # Modify this configuration item as follows
    # Then in the root directory of the project, create a new templates directory to store html files
    'DIRS': [
        os.path.join(BASE_DIR, 'templates')
    'APP_DIRS': True,
    'OPTIONS': {
            'context_processors': [

css, js, image file configuration: at the end of the file

STATIC_URL = '/static/'  # Under the project root helloworld

# Of course, there's also the use of aliases. At the beginning, it's useless to talk more about them

How to reference css, js in html

<!DOCTYPE html>
<html lang="en">
    <script src='/static/test.js'></script>


Normative items

Some of the above writing methods are mostly used for practice, so they are not standard. For example, we wrote a lot of functions in helloword/helloword/, which is very unsightly. So now introduce a new thing.

  1. In the project root directory, execute

     python3 startapp app (module name)
     #This is the second time we use the file,
     #The first time is to start the project. Now you can understand why this file is used
     #After execution, we will find that there is an app directory in the root directory of the project

  1. Let django know your new app module

     		# Newly added 
             'app.apps.AppConfig'  # You can also write 'app' directly
     		# app is the fixed after the new directory name,
     		# You can also open the app/ file to see
  2. There is a file in the app directory. We can define the function here.

     from django.shortcuts import HttpResponse, render, redirect
     def index(request):
         return render(request, 'index.html')
  3. Then go back to helloword/helloword/ file, and modify it as follows:

     # 1. Import function
     from app.views import index
     # 2. configuration
     urlpatterns = [
         url(r'^index/', index),


How to configure mysql database

Also find a file under helloworld/helloworld /, about 70-80 lines

Revised as follows:

    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'student_sys', # library
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': 'localhost',
        'PORT': 3306

Then find the helloworld/app/ file

The file is empty by default. Add the following configuration

import pymysql

# Tell django to replace mysqldb with pymysql

Introducing orm

Enter the helloworld/app / directory to find the file. Modify it as follows:

from django.db import models

# Define a Student class
class Student(models.Model):
    id = models.AutoField(primary_key=True) # Primary key
    name = models.CharField(max_length=20) # Character type
    sex = models.CharField(max_length=2)
    birthday = models.CharField(max_length=10)

    def __str__(self):
        return + "\t" + + "\t" + self.birthday

Execute in sequence under the project root directory helloworld

python3 makemigrations

python3 migrate

It will automatically generate tables for us

You may also be confused:

  1. Why do we define a model and generate so many tables
  2. How to update the table structure automatically after modifying the model
  3. How to crud and so on

Please explore by yourself


Self Tucao: in fact, such a tutorial is very tasteless, worried that the space is too long to see people dazzled.

  • There is no explanation in many places, such as the configuration of, automatic table generation, etc
  • There are many questions left that have not been answered, and even some questions have not been mentioned in the article. For example, 403 will appear on the visit page, how to solve them
  • The reason why I didn't talk so much is that I think those problems are easy to solve

After finishing writing, I feel that the location of this article is more self summarization. Maybe you can see this article will vomit slot, spray me ~ ~ ~

Keywords: Programming Django Python Database MySQL

Added by neex1233 on Fri, 31 Jan 2020 13:03:59 +0200