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.

Attached:

  1. Official course: https://docs.djangoproject.com/en/3.0/intro/tutorial02/
  2. Rookie tutorial: https://www.runoob.com/django/django-tutorial.html

text

My development environment

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

Preparation

  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. settings.py is mainly for some configurations, such as database, static file storage location, etc
 3. urls.py mainly configures the mapping relationship between URLs and functions
 4. manage.py 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 manage.py runserver
    // You can also specify ip: host
    python3 manage.py 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 urls.py file under helloworld/helloworld /

Default configuration:

    from django.conf.urls import url
    from django.contrib import admin
   
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
    ]

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 = [
        url(r'^admin/', admin.site.urls),
        # 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 settings.py file below

html file configuration: about more than 50 lines

TEMPLATES = [
{
    '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': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

css, js, image file configuration: at the end of the settings.py 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">
<head>
    <script src='/static/test.js'></script>
    <title>Document</title>
</head>
<body>

</body>
</html>

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/urls.py, which is very unsightly. So now introduce a new thing.

  1. In the project root directory, execute

     python3 manage.py startapp app (module name)
    
     #This is the second time we use the file manage.py,
     #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

      INSTALLED_APPS = [
             'django.contrib.admin',
             'django.contrib.auth',
             'django.contrib.contenttypes',
             'django.contrib.sessions',
             'django.contrib.messages',
             'django.contrib.staticfiles',
     		# 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/apps.py file to see
         ]
    
  2. There is a view.py 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/urls.py file, and modify it as follows:

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

additional

How to configure mysql database

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

Revised as follows:

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

Then find the helloworld/app/init.py file

The file is empty by default. Add the following configuration

import pymysql

# Tell django to replace mysqldb with pymysql
pymysql.install_as_MySQLdb()

Introducing orm

Enter the helloworld/app / directory to find the models.py 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 self.name + "\t" + self.sex + "\t" + self.birthday

Execute in sequence under the project root directory helloworld

python3 manage.py makemigrations

python3 manage.py 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

summary

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 settings.py, 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