A very detailed introduction to Django development (with pictures and texts)

1. Django overview

Django is an open source web application framework written in Python. The framework pattern of MTV is adopted, that is, model M, view V and template T.

The core components of the Django framework are:

  • Object-relational mapping for creating models;
  • Design a better management interface for end users;
  • URL design;
  • Designer-friendly templating language;
  • caching system.

Django has become the framework of choice for web developers and is a framework that follows the MVC design pattern. MVC is an abbreviation of the three words Model, View, and Controller, which represent model, view, and controller respectively. Django is actually an MTV design pattern.

MTV is an abbreviation of the three words Model, Template, and View, which represent model, template, and view respectively. But in Django, the part where the controller accepts user input is handled by the framework itself, so Django pays more attention to the model (Model), template (Template) and view (Views), which is called MTV mode. Their respective responsibilities are as follows:

insert image description here

2. Django project environment construction

To build a Django development environment, there are mainly the following six steps

2.1 Create and activate a virtual environment

cd D:\djangotest #自己创建空文件夹存放项目
python -m venv djangoenv #创建虚拟环境

picture

Run the following command to activate the virtual environment

cd D:\djangotest
djangoenv\Scripts\activate #激活虚拟环境

 2.2 Install django module

#1激活虚拟环境
cd D:\djangotest
djangoenv\Scripts\activate
#2安装django模块
pip install Django #激活虚拟环境后安装Django模块

 

After the above command is executed , the Django module will be installed under djangoenv/Lib/site-packages, that is to say, this Django module is only installed in the virtual environment, not in the Python global environment. The directory is shown in the figure below

insert image description here

2.3 Create a Django project

After installing Django, we can use Django's management tool------>django-admin

We create a Django project named loginweb with the following command:

#1激活虚拟环境
cd D:\djangotest
djangoenv\Scripts\activate
#2创建一个loginweb的项目
django-admin startproject loginweb
或者
python -m django startproject loginweb

After this command is executed, a Django project named loginweb will be created in the same directory as djenv. The directory structure is shown in the figure below:

insert image description here

Open the project with Pycharm, the meaning of the project structure file is as follows:

The outer loginweb directory: is the container of the project, Django doesn't care about its name, we can rename it to any name we like

Inside the loginweb directory: it is a pure python package. We can call it the name of the project, it cannot be renamed at will

manage.py: It is a very important tool of Django, through which you can call django shell and database, such as: create app application, create database table, clear data, start project and other operations

settings.py : The configuration file for the Django project. Contains default settings for the project, including database information, debug flags, and other working variables

urls.py : The URL routing declaration for the Django project, responsible for mapping URL patterns to applications

wsgi.py: Web server gateway interface (abbreviation of Python Web Server Gateway Interface), an interface between Python applications and Web servers, which can be regarded as a protocol and specification. It is based on the Http protocol and does not support WebSocket

asgi.py: Asynchronous gateway protocol interface, which can handle a variety of common protocol types, including HTTP, HTTP2 and WebSocket, which can be regarded as ASGI is an extension of WSGI

3. Django development login function

3.1 Create an app application

Generally, a project contains multiple app applications (of course, a general app can also be used in multiple projects) Next, we create a login for the loginweb project

#1激活虚拟环境
cd D:\djangotest
djangoenv\Scripts\activate
#2切到django项目中
cd loginweb
#3创建一个叫login的应用
django-admin startapp login

insert image description here

After the above command is executed, the directory structure is as shown in the figure below

picture

3.2 Register app

After the app application is created, the app must be registered with Django before it can be managed by the Django project. We only need to configure the name of the login application into the loginweb/settings.py file. As shown below:

picture

3.3 Django view

What Django views do : Simple Python functions that accept web requests and return web responses. This function is generally defined in the views.py file of the respective application. In the view function, there are two important objects: request object and response object.

Here is the simplest view function:

# 例:在login/views.py 中
from django.http import HttpResponse
# Create your views here.

def login(request):
  return HttpResponse("登录页面")

Among them: the request parameter is a required parameter, representing the user's request, which is an HttpRequest object

3.4 Django Routing

Django's routing definition file is: project directory urls.py file. All our routing configurations are defined in the urls.py file in the form of a list, adding the routing we want

# 例:在loginweb/urls.py 中
from django.contrib import admin
from django.urls import path
from login import views
urlpatterns = [
   path("admin/", admin.site.urls),
   path("login/",views.login)
]

3.5 Start the Django project

In the development environment, we need to start the Django project locally to develop and debug our code. The command to start the Django project is as follows:

python manage.py runserver [port]
#[port] 为应用访问端口,可以缺省不写,默认为8000。

At this point, we can access our project with a browser. The result is shown in the figure below

picture

Visit our written route

picture

3.6 Improved login function

Create a new templates directory under login to store the written html front-end page

picture

 login.html

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>登录页面</title>
   <style>
       body{
       text-align:center;
      }
   </style>
</head>
<body>
<form action="/login/" method="post">
  {% csrf_token %}
   <h1 align="center">登录页面</h1>
   <p class="divs">
       <label for="username">用户名:</label>
       <input type="text" id="username" name="username" align="center">
   </p>
   <p class="divs">
       &nbsp&nbsp&nbsp<label for="password">密码:</label>
       <input type="password" id="password" name="password">
   </p>
   <input type="submit" value="登录">
   <span style="color:red">{
   
   { error }}</span>
</form>


</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>这里是主页</title>
   <style>
       h1 { color:red }
   </style>
</head>
<body>
   <h1>这里是主页</h1>
</body>
</html>

modify view function

from django.shortcuts import render,redirect
# Create your views here.

def login(request):
  if request.method == 'POST':
     username = request.POST.get('username')
     passowrd = request.POST.get('password')
     if username=='songqin' and passowrd =='123456':
        return redirect('/index')
     else:
        return render(request,'login.html',{"error":"用户名或密码错误"})

  return render(request,'login.html')

def index(request):
  return render(request,'index.html')

Modify loginweb/urls.py

from django.contrib import admin
from django.urls import path
from login import views
urlpatterns = [
   path("admin/", admin.site.urls),
   path("login/",views.login),
   path("index/",views.index)
]

Start the Django project again

python manage.py runserver [port]
#[port] 为应用访问端口,可以缺省不写,默认为8000。

Visit http://127.0.0.1:8000/login/project

insert image description here

The input is not a username and password is not songqin/123456

insert image description here

Enter songqin/123456 and click login to jump to the main page

picture

Finally:  I have compiled a complete set of software testing learning tutorials for you, and friends can get it for free if they need it 【保证100%免费】

Information acquisition method:
This document and video information should be the most comprehensive and complete preparation warehouse for friends who want to engage in [software testing]. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. Hope Can help you too! All of the above can be shared, click the small card below to enter the group to receive.

Guess you like

Origin blog.csdn.net/NHB456789/article/details/131207493