Let me take notes - Django development process and configuration

Stick wing 2021-01-21 20:58:11
let notes django development process

Environmental Science Ubuntu20.04Django1.11.1

1.Django Introduce

Django Of The main purpose is to simplify 、 Fast development of database driven websites . It emphasizes code reuse , Multiple components can be easily used to " plug-in unit " Form serves the whole framework ,Django There are many powerful third-party plug-ins , You can even easily develop your own toolkit . This makes Django It has strong scalability . It also emphasizes rapid development and DRY(DoNotRepeatYourself) principle .

1.1 Heavyweight framework

contrast Flask frame ,Django Native provides many functional components , Make development easier and faster .

  • Provides automated scripting tools for project management
  • database ORM Support ( Object relation mapping , English :Object Relational Mapping)
  • Templates
  • Forms
  • Admin Manage site
  • file management
  • Authentication authority
  • session Mechanism
  • cache

1.2 MVC Mode description

  • M Put it all together Model, It mainly encapsulates the access to the database layer , Add data to database 、 Delete 、 Change 、 Check operation .
  • V Put it all together View, Used to encapsulate results , Generate page displayed html Content .
  • C Put it all together Controller, For receiving requests , Process business logic , And Model and View Interaction , Return results .

1.3 Django Of MVT

  • M Put it all together Model, And MVC Medium M Function the same , Responsible for interacting with database , Data processing .
  • V Put it all together View, And MVC Medium C Function the same , Receiving request , Conduct business processing , Back to answer .
  • T Put it all together Template, And MVC Medium V Function the same , Responsible for encapsulating the returned html.

1.4 Django Configuration order

bookmanager: For project catalog ;
book: For the application directory ;
bookmanager/settings.py -->> bookmanager/urls.py -->>
book/urls.py -->> book/views.py -->> templates/book/index.html
-->> book/models.py -->> database

1. establish Django project

django-admin startproject bookmanager
After execution , There will be a new directory called bookmanager, This is the newly created project directory .
  • A directory with the same name as the project , Here is bookmanager.
  • settings.py Is the overall configuration file of the project .
  • urls.py It's the project URL The configuration file .
  • wsgi.py It's the project and WSGI Compatible Web Server portal .
  • manage.py It's a project management document , Manage projects through it .

The command to run the server is as follows :

# vim ./bookmanager/settings.py Set in ALLOWED_HOSTS = ['*']
# After setting, it can be accessed remotely ip
python manage.py runserver ip: port
or :
python manage.py runserver

2. establish Django Subapplication

stay django in , Creating sub application module directory can still be operated by command , namely :

python manage.py startapp Subapplication name
for example :cd ~/book
python manage.py startapp book
After execution , You can see that there is an extra one named book A subdirectory
  • admin.py File with the site's background management site configuration related .
  • apps.py The file is used to configure information about the current subapplication .
  • migrations Directory is used to store database migration history files .
  • models.py File users save database model classes .
  • tests.py Files are used to develop test cases , Write unit tests .
  • views.py Files are used to write Web Application view .

3. Register to install subapplications

In the project configuration file settings.py in ,INSTALLED_APPS Item to save the subapplications that have been registered and installed in the project , In the initial project INSTALLED_APPS as follows :

for example , Will just create book Add sub applications to the project , Can be found in INSTALLED_APPS Add... To the list 'book.apps.BookConfig'.

vim ./bookmanager/settings.py
# Application definition
# Add your own sub app

4. Use Django Database development

4.1. Define model classes

Sub application directory models.py Define model classes in , Inherited from models.Model

from django.db import models
# Create your models here.
# Model class for preparing book list information
class BookInfo(models.Model):
# Create fields , Field type ...
name = models.CharField(max_length=10)
# Prepare the model class of person list information
class PeopleInfo(models.Model):
name = models.CharField(max_length=10)
gender = models.BooleanField()
# Foreign key constraints : Which book does the character belong to
book = models.ForeignKey(BookInfo)

4.2. Model migration ( Build table )

  • According to the sub application directory models.py Generate statements to create tables and create tables in the database

  • Generate migration file : Generate the statement to create the table according to the model class

    python manage.py makemigrations
    Sub application directory makemigrations The directory will generate 0001_initial.py
  • Perform the migration : Create the table in the database according to the statement generated in the first step

    python manage.py migrate
  • Tips : By default sqlite3 Database to store data

5. Site management

5.1. Localization of management interface

Django Project directory settings.py Set Chinese and time zone :

# Set up Chinese
# Asian Shanghai time zone
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True

5.2 Create administrator

Create the administrator's command :

 python manage.py createsuperuser
# Enter the management user name and password according to the prompt
  • Reset password

  • python manager.py changepassword user name

Start the service : python manage.py runserver ip: port

Landing site : Management database .

In the sub application directory models.py Optimization model class display :

# Model class for preparing book list information
class BookInfo(models.Model):
# Create fields , Field type ...
name = models.CharField(max_length=10)
def __str__(self):
""" Output the model class as a string """
return self.name # In the website management list, you can see name attribute

6. The view and URL

6.1. Define view functions

In the sub application directory views.py It defines

  • A view is a Python function , Is defined in application Of views.py in .
  • The first parameter of the view is HttpRequest Object of type reqeust, It includes everything Request information .
  • The view must return to HttpResponse object , Contains the... Returned to the requester Response information .
  • Import required HttpResponse modular :from django.http import HttpResponse
  • Define view functions : Response string OK! To the client
# vim ./book/views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse('OK!!!')

6.2. To configure URLconf

The process of finding views :

  • 1. The requester enters in the browser address bar URL, Request to the website .
  • 2. Website access URL Information .
  • 3. And then with the written URLconf Match one by one .
  • 4. If the match is successful, call the corresponding view .
  • 5. If all URLconf There's no match . Then return to 404 error .

In the project catalog settings.py Set up URLconf entrance :

# vim ./bookmanager/settings.py
ROOT_URLCONF = 'bookmanager.urls'
  • Two steps to complete URLconf To configure
    • 1. stay project In the definition of URLconf
    • 2. stay application In the definition of URLconf
  • stay project In the definition of URLconf
# vim ./bookmanager/urls.py
from django.conf.urls import url,include # Import
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
# Regular matching rules : As long as it's not admin/ Even if the match is successful
url(r'^', include('book.urls'))
  • stay application In the definition of URLconf
# Create a new... In the sub application directory urls.py
# vim ./book/urls.py
from django.conf.urls import url
from book.views import index
# urlpatterns For fixed writing
urlpatterns = [
url(r'^$',index) # Route bootstrap view function

7. Templates

7.1 How to use the template

  • 1. Create a template
  • 2. Set the template lookup path
  • 3. The template receives data from the view
  • 4. Template processing data

7.2 Create a template

  • stay application Create a template folder in the same level directory templates. The folder name is written in a fixed way .
  • stay templates Under the folder , establish application Folder with the same name . example , Book
  • stay application Create a folder with the same name Web template file . example :index.html

7.3 Set the template lookup path

Under the project directory , vim bookmanager/setings.py Set up DIRS

'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'context_processors': [

7.4. The template receives data from the view

 Write in the sub application directory :
vim book/views.py
# -*- coding:utf-8 -*-
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
context = {'title':' Test template data '}
return render(request, 'book/index.html', context)

7.5. Template processing data

# Write template data html、css、js etc.
vim templates/book/index.html
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title> Test template data </title>
<h1> Data in the root path </h1>
<di style="background: red; font-size: 30px"> {{title}} </di>

7.6. View the results of template processing data

1. Run the server : python manage.py runserver

2. Enter in server : visit

8. The database data is displayed on the web page

Implementation steps :

  • 1. Create view
  • 2. Create a template
  • 3. To configure URLconf

8.1 Create view

  • Query database data
  • Construction context
  • Pass context to template
 Sub application directory : vim book/views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from book.models import BookInfo,PeopleInfo
# BookInfo,PeopleInfo Model class , stay 4.1 The definition has migrated
def index(request):
context = {'title':' Test template data '}
return render(request, 'book/index.html', context)
# Define views : Provide book list information
def bookList(request):
# Query database book list data
books = BookInfo.objects.all()
# Construction context
context = {'books':books}
# The data is sent to the template for processing , After the processing is completed, the response is sent to the client through the view
return render(request, 'book/booklist.html', context)

8.2. Create a template

  • Read context data
  • Building a web page html file : Book information is shown in a list style
 In the template directory :
vim templates/book/booklist.html
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title> Book list information </title>
{% for book in books %}
<li>{{ book.name }}</li>
{% endfor %}

8.3. To configure URLconf

Modifier application In the directory urls.py file

from django.conf.urls import url
from book.views import index,bookList
urlpatterns = [
# Matching book list information URL, Call corresponding bookList View

cd $HOME/bookmanager

Start the service : python manage.py runserver

Type in the browser

You can see the data in the database .

9. Configuration files and static files

9.1 setting The configuration file

BASE_DIR attribute :

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

The root of the current project ,Django Will be based on this to locate the relevant documents within the project , We can also use this parameter to construct the file path .

DEBUG attribute :

Debug mode , After creating the project, the initial value is True, That is, it works in debug mode by default .

effect :

  • Modify the code file , The program restarts automatically

  • Django When the program is abnormal , Show detailed error tracking information to the front end

  • Not in debug mode , Return only Server Error (500)

Be careful : Deploy online Django Don't run in modal mode , Remember to revise DEBUG=False and ALLOWED_HOSTS( visit ip).

Set the local language and time zone

LANGUAGE_CODE = 'en-us' # Language
TIME_ZONE = 'UTC' # The time zone # The time zone

Modifying language and time zone to Chinese mainland

TIME_ZONE = 'Asia/Shanghai'

9.2 Static files

In the project CSS、 picture 、js All static files . Static files are usually placed in a separate directory .

To provide static files , You need to configure two parameters :

  • STATICFILES_DIRS The directory where static files are located
  • STATIC_URL Access to static files URL Prefix

1) Create... In the project root directory static Directory to save static files .

2) stay bookmanager/settings.py The two parameters to modify the static file in are

STATIC_URL = '/static/'
os.path.join(BASE_DIR, 'static'),

3) At this time in static Any static file you add can use the URL /static/ The file in static In the path Came to visit. .

for example , We ask static Add a index.html file , You can use it in your browser To visit .

9.3App Application configuration

We add this class to the project settings.py Medium INSTALLED_APPS In the list , Indicates that an application with this configuration property is registered and installed .

# Add your own sub app

At every In the application directory It's all about apps.py file , Used to save information about the app .

When creating an app ,Django Will send to apps.py Write a configuration class of the application in the file , Such as

from django.apps import AppConfig
class BookConfig(AppConfig):
name = 'book'
  • AppConfig.name Property indicates to which application the configuration class is loaded , Each configuration class must contain this property , Automatically generated by default .

  • AppConfig.verbose_name Property is used to set the intuitive and readable name of the app , The name is in Django Provided Admin The administration site will display , Such as

    from django.apps import AppConfig
    class UsersConfig(AppConfig):
    name = 'book'
    verbose_name = ' Book management '
本文为[Stick wing]所创,转载请带上原文链接,感谢

  1. Centos7 installing Python 3.8
  2. Centos7 installing Python 3.8
  3. Django——图书管理系统(六)
  4. Django——图书管理系统(五)
  5. Django -- library management system (6)
  6. Django -- library management system (5)
  7. python批量插入数据小脚本
  8. Python batch insert data script
  9. ZoomEye-python 使用指南
  10. Zoomeye Python User's Guide
  11. 用Python写代码,一分钟搞定一天工作量,同事直呼:好家伙 - 知乎
  12. Using Python to write code, one minute to complete a day's workload, colleagues call: good guy - Zhihu
  13. Python 上的可视化库——PyG2Plot
  14. Pyg2plot: a visualization library on Python
  15. Python 上的可视化库——PyG2Plot
  16. Python实用代码-无限级分类树状结构生成算法
  17. Pyg2plot: a visualization library on Python
  18. Python utility code - infinite classification tree structure generation algorithm
  19. 奇技淫巧,还是正统功夫?Python推导式最全用法
  20. Pandas 的这个知识点,估计 80% 的人都得挂!
  21. 前后端分离有什么了不起,手把手教你用Python爬下来!
  22. 在 Azure 上执行一些简单的 python 工作
  23. 推荐 :利用Python的混合集成机器学习(附链接)
  24. Cunning or orthodox Kung Fu? The most complete usage of Python derivation
  25. It's estimated that 80% of pandas people have to hang up!
  26. What's so great about the separation of front and rear ends? Hand in hand teach you to climb down with Python!
  27. Doing some simple Python work on azure
  28. Recommendation: hybrid integrated machine learning using python (link attached)
  29. Learning PPO algorithm programming from scratch (Python version)
  30. Python OpenCV 图片模糊操作 blur 与 medianBlur
  31. Python OpenCV image blur operation blur and mediablur
  32. 成功解决cv2.error: OpenCV(4.1.2) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: err
  33. Cv2.error solved successfully: opencv (4.1.2) C:: (projects / opencv Python / opencv modules / imgproc / SRC)\ color.cpp:182 : err
  34. Python 中使用 virtualenv 管理虚拟环境
  35. Using virtualenv to manage virtual environment in Python
  36. 如何使用Python执行系统命令?Python学习教程!
  37. How to use Python to execute system commands? Python tutorial!
  38. 快速掌握Python中的循环技术
  39. Quickly grasp the loop technology in Python
  40. Python主流Web框架之Tornado
  41. appium+python自动化63-使用Uiautomator2报错问题解决
  42. Tornado: the mainstream Python Web Framework
  43. Appium + Python automation 63 - using uiautomator2 to solve the problem of error reporting
  44. 爬虫+django,打造个性化API接口
  45. Crawler + Django to create personalized API interface
  46. 爬虫+django,打造个性化API接口
  47. Crawler + Django to create personalized API interface
  48. C、C++、Java、PHP、Python主要应用在哪里方面?
  49. C. Where are the main applications of C + +, Java, PHP and python?
  50. Python 无限级分类树状结构生成算法 「实用代码」
  51. Python infinite classification tree structure generation algorithm "practical code"
  52. 【Azure 存储服务】Python模块(azure.cosmosdb.table)直接对表存储(Storage Account Table)做操作示例
  53. [azure storage service] Python module( azure.cosmosdb.table )Direct operation example of storage account table
  54. 【Azure 存储服务】Python模块(azure.cosmosdb.table)直接对表存储(Storage Account Table)做操作示例
  55. [azure storage service] Python module( azure.cosmosdb.table )Direct operation example of storage account table
  56. openpose c++ 配置教程 + python api
  57. Openpose C + + configuration tutorial + Python API
  58. PYTHON爬虫实战_垃圾佬闲鱼爬虫转转爬虫数据整合自用二手急速响应捡垃圾平台_3(附源码持续更新)
  59. 使用python javaSerializationTools模块拼接生成 8u20 Gadget
  60. 萌新入门之python基础语法