23. Django basics

23. Django basics

Django basic configuration

Python's WEB frameworks include Django, Tornado, Flask, etc. Compared with other WEB frameworks, Django has the following advantages: large and complete. The framework itself integrates ORM, model binding, template engine, cache, Session and many other functions.

1. Installation

# windows install directly with pip
pip install django
 
# The generated django file is added to the system environment variable

2. Create and start

create
django-admin startproject mysite

run
python manage.py runserver 127.0.0.1:8001

Browser access:
http://127.0.0.1:8001/

3.mysite directory structure

mysite #directory
 -mysite # Configure the entire program
  -init
  -settings # configuration file
  -urls # URL correspondence
  -wsgi # Follow the WSIG specification, uwsgi + nginx
 -manage.py # Manage Django program:

Django business configuration

1. Create the app

python manage.py startapp cmdb --> Run in Terminal

2.app directory structure

# Directory Structure
-cmdb
    -migrations #Database operation record (just the record of modifying the table structure)
    -init # means python data package (with or without python3)
    -admin #Django provides us with background management
    -apps #Configure the current app
    -models #Create the database table structure, write the specified class, and create the database structure through the command
    -tests #unit test
    -views #Write business logic code, the most important thing is this file

3.templates

(1) Generate the login page to be displayed to the user in the templates directory

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        label{
            width: 80px;
            text-align: right;
            display: inline-block;
        }
    </style>
</head>
<body>
    <form action="/login" method="post">
        <p>
            <label for="username">Username:</label>
            <input id="username" name="user" type="text"/>
        </p>
        <p>
            <label for="password">Password:</label>
            <input id="password" name="pwd" type="password"/>
            <input type="submit" value="Submit"/>
        </p>
    </form>
</body>
</html>

(2) Modify the urls file to increase the login path

from django.conf.urls import url
from django.contrib import admin
from cmdb import views #import views module

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login', views.login), #Add the url of login.html, followed by a comma
]

(3) Modify the view file and process the data

from django.shortcuts import HttpResponse
from django.shortcuts import render
 
def login(request):
    return render(request,'login.html')
 
    # The above code is equivalent to this
    # f = open('templates/login.html','r',encoding='utf-8')
    # data = f.read()
    # f.close()
    # return HttpResponse(data)

(4) Configure the static path of static files

The static file static contains css and js files. If you want to display the corresponding styles, you must first modify the settings file configuration

# Add the following content in the settings.py file

After configuring Road King, you can use css and js files

Django form interaction

1. Obtain the form submission type and deal with it accordingly. Enter the user name and password correctly and jump to the page, and there will be a prompt message for input errors

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/commons.css"/>
    <style>
        label{
            width: 80px;
            text-align: right;
            display: inline-block;
        }
    </style>
</head>
<body>
    <form action="/login/" method="post">
        <p>
            <label for="username">Username:</label>
            <input id="username" name="user" type="text"/>
        </p>
        <p>
            <label for="password">Password:</label>
            <input id="password" name="pwd" type="password"/>
            <input type="submit" value="Submit"/>
            <span style="color: red;">{{ error_msg }}</span>
        </p>
    </form>

</body>
</html>
from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect


def login(request):
    # request contains all the information submitted by the user
    # print(request.method)

    error_msg =''
    if request.method =='POST':
        user = request.POST.get('user', None)
        pwd = request.POST.get('pwd', None)
        if user =='root' and pwd == '123':
            # Go to jump
            return redirect('http://www.baidu.com')
        else:
            error_msg ='Username or password is wrong'

    return render(request,'login.html', {'error_msg': error_msg})

2. Simulate database interaction

Access the login interface, the user enters the user name to jump to the home page

(1) Landing page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/commons.css"/>
    <style>
        label{
            width: 80px;
            text-align: right;
            display: inline-block;
        }
    </style>
</head>
<body>
    <form action="/login/" method="post">
        <p>
            <label for="username">Username:</label>
            <input id="username" name="user" type="text"/>
        </p>
        <p>
            <label for="password">Password:</label>
            <input id="password" name="pwd" type="password"/>
            <input type="submit" value="Submit"/>
            <span style="color: red;">{{ error_msg }}</span>
        </p>
    </form>

</body>
</html>

(2)home page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body style="margin: 0">
    <div style="height: 48px;background-color: #dddddd"></div>
    <div>
        <form action="/home/" method="post">
            <input type="text" name="username" placeholder="Username"/>
            <input type="text" name="email" placeholder="Mailbox"/>
            <input type="text" name="gender" placeholder="gender"/>
            <input type="submit" value="add"/>
        </form>
    </div>
    <div>
        <table>
            {% for row in user_list %}
                <tr>
                    <td>{{ row.username }}</td>
                    <td>{{ row.gender }}</td>
                    <td>{{ row.email }}</td>
                </tr>
            {% endfor %}

        </table>
    </div>


</body>
</html>

(3) Modify the view file and process the input content

from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect

def login(request):
    # request contains all the information submitted by the user
    # print(request.method)

    error_msg =''
    if request.method =='POST':
        user = request.POST.get('user', None)
        pwd = request.POST.get('pwd', None)
        if user =='root' and pwd == '123':
            # Go to jump
            return redirect('/home')
        else:
            error_msg ='Username or password is wrong'

    return render(request,'login.html', {'error_msg': error_msg})

USER_LIST = [
    {'id': 1,'username':'derek','email': '111', "gender":'Male'},
    {'id': 2,'username':'jack','email': '222', "gender":'女'},
    {"id": 3,'username':'tom','email': '333', "gender":'Male'},
]

def home(request):
    if request.method == "POST":
        # Get the data submitted by the user in the POST request
        u = request.POST.get('username')
        e = request.POST.get('email')
        g = request.POST.get('gender')
        temp = {'username': u,'email': e, "gender": g}
        USER_LIST.append(temp)
    return render(request,'home.html', {'user_list': USER_LIST})

3. Get multiple values ​​of checkbox

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login/" method="POST">
        <p>
            111: <input type="checkbox" name="favor" value="11"/>
            222: <input type="checkbox" name="favor" value="22"/>
            333: <input type="checkbox" name="favor" value="33"/>
        </p>
        <input type="submit" value="Submit"/>
    </form>
</body>
</html>

Modify the views.py file to process the form

from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect


def login(request):
    #checkbox Checkbox
    if request.method == "POST":
        favor_list = request.POST.getlist("favor") #getlist gets multiple values
        print(favor_list) #The multi-select box gets the list format
        #['11', '22', '33']
        return render(request,"login.html")
    elif request.method == "GET":
        return render(request,"login.html")
    else:
        print("other")

After the user submits, the information submitted by the user can be obtained in the background, as shown below

4. Upload file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login" method="POST" enctype="multipart/form-data">
        <p>
            <input type="file" name="files"/>
        </p>
        <input type="submit" value="Submit"/>
    </form>
</body>
</html>

views.py

from django.shortcuts import render,HttpResponse
import os
def login(request):
    #file Upload file
    if request.method == "POST":
        obj = request.FILES.get('files') #Get file objects with files
        if obj:
            print(obj, type(obj), obj.name)
            # test.jpg <class'django.core.files.uploadedfile.InMemoryUploadedFile'> test.jpg
            import os
            file_path = os.path.join('upload', obj.name) #The way to save files uploaded by users
            f = open(file_path, "wb")
            for item in obj.chunks(): #chunks represents all data chunks and is an iterator
                f.write(item)
            f.close()
        return render(request,"login.html")
    elif request.method == "GET":
        return render(request,"login.html")
    else:
        print("other")
Reference: https://cloud.tencent.com/developer/article/1091568 23. Django Basics-Cloud + Community-Tencent Cloud