前提条件(选配)
安装Django
(py_huanjing01) [root@WzcWyt ~]# pip install django
Looking in indexes: http://mirrors.cloud.aliyuncs.com/pypi/simple/
Collecting django
Downloading http://mirrors.cloud.aliyuncs.com/pypi/packages/cf/91/e23103dd21fa1b5c1fefb65c4d403107b10bf450ee6955621169fcc86db9/Django-3.2.2-py3-none-any.whl (7.9 MB)
|████████████████████████████████| 7.9 MB 1.4 MB/s
Collecting sqlparse>=0.2.2
Downloading http://mirrors.cloud.aliyuncs.com/pypi/packages/14/05/6e8eb62ca685b10e34051a80d7ea94b7137369d8c0be5c3b9d9b6e3f5dae/sqlparse-0.4.1-py3-none-any.whl (42 kB)
|████████████████████████████████| 42 kB 32.2 MB/s
Collecting asgiref<4,>=3.3.2
Downloading http://mirrors.cloud.aliyuncs.com/pypi/packages/17/8b/05e225d11154b8f5358e6a6d277679c9741ec0339d1e451c9cef687a9170/asgiref-3.3.4-py3-none-any.whl (22 kB)
Collecting pytz
Downloading http://mirrors.cloud.aliyuncs.com/pypi/packages/70/94/784178ca5dd892a98f113cdd923372024dc04b8d40abe77ca76b5fb90ca6/pytz-2021.1-py2.py3-none-any.whl (510 kB)
|████████████████████████████████| 510 kB 100.3 MB/s
Installing collected packages: sqlparse, pytz, asgiref, django
Successfully installed asgiref-3.3.4 django-3.2.2 pytz-2021.1 sqlparse-0.4.1
(py_huanjing01) [root@WzcWyt ~]# pip list
Package Version
---------- -------
asgiref 3.3.4
Django 3.2.2
pip 21.1.1
pytz 2021.1
setuptools 56.0.0
sqlparse 0.4.1
wheel 0.36.2
(py_huanjing01) [root@WzcWyt ~]#
创建项目
(py_huanjing01) [root@WzcWyt djangoxuni]# django-admin startproject test01
(py_huanjing01) [root@WzcWyt djangoxuni]# ll
total 0
drwxr-xr-x 3 root root 37 May 11 10:56 test01
(py_huanjing01) [root@WzcWyt djangoxuni]# cd test01/
(py_huanjing01) [root@WzcWyt test01]# ll
total 4
-rwxr-xr-x 1 root root 662 May 11 10:56 manage.py
drwxr-xr-x 2 root root 89 May 11 10:56 test01
(py_huanjing01) [root@WzcWyt test01]# tree
.
├── manage.py
└── test01
├── asgi.py
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
1 directory, 6 files
(py_huanjing01) [root@WzcWyt test01]#
目录解释
manage.py:是项目管理文件,通过它管理项目。
test01:与项目同名的目录。
asgi:作为你的项目的运行在 ASGI 兼容的 Web 服务器上的入口。
__init__.py:是一个空文件,作用是这个目录test01可以被当作包使用。
settings.py:是项目的整体配置文件。
urls.py:是项目的URL配置文件。
wsgi.py:作为你的项目的运行在 WSGI 兼容的Web服务器上的入口。
进入test01项目创建应用
(py_huanjing01) [root@WzcWyt test01]# python manage.py startapp user
(py_huanjing01) [root@WzcWyt test01]# ll
total 4
-rwxr-xr-x 1 root root 662 May 11 10:56 manage.py
drwxr-xr-x 3 root root 108 May 11 11:16 test01
drwxr-xr-x 3 root root 123 May 11 11:16 user
(py_huanjing01) [root@WzcWyt test01]# cd user/
(py_huanjing01) [root@WzcWyt user]# tree
.
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
1 directory, 7 files
(py_huanjing01) [root@WzcWyt user]#
目录解释
admin:该应用的后台管理系统配置
apps:该应用的一些配置,Django-1.9以后自动生成
__init__.py:是一个空文件,表示当前目录可以当作一个python包使用。
migrations:数据移植(迁移)模块,内容自动生成
__init__.py:是一个空文件,表示当前目录可以当作一个python包使用。
tests.py:用于开发测试用例。
models.py:跟数据库操作相关。
views.py:跟接收浏览器请求,进行处理,返回页面相关。
修改test01下settings.py进行应用注册
通常, INSTALLED_APPS 默认包括了以下 Django 的自带应用:
django.contrib.admin – 管理员站点, 你很快就会使用它。
django.contrib.auth – 认证授权系统。
django.contrib.contenttypes – 内容类型框架。
django.contrib.sessions – 会话框架。
django.contrib.messages – 消息框架。
django.contrib.staticfiles – 管理静态文件的框架。
(py_huanjing01) [root@WzcWyt test01]# vim settings.py
"""
Django settings for test01 project.
Generated by 'django-admin startproject' using Django 3.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=-ek7u#wp$jx5iydbq7ry(%^o6!bf)k0#&l2m1&6afyr%y-*er'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'user', # 应用注册============================
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'test01.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'test01.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
启动验证
(py_huanjing01) [root@WzcWyt test01]# ll
total 4
-rw-r--r-- 1 root root 0 May 11 13:38 db.sqlite3
-rwxr-xr-x 1 root root 662 May 11 10:56 manage.py
drwxr-xr-x 3 root root 108 May 11 13:42 test01
drwxr-xr-x 4 root root 142 May 11 13:40 user
(py_huanjing01) [root@WzcWyt test01]# python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
May 11, 2021 - 05:42:48
Django version 3.2.2, using settings 'test01.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
浏览器访问:http://127.0.0.1:8000/
修改settings.py文件配置本地化
# 中文
LANGUAGE_CODE = ‘zh-hans’
# 上海时间内
TIME_ZONE = ‘Asia/Shanghai’
"""
Django settings for test01 project.
Generated by 'django-admin startproject' using Django 3.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '70)@b^z0+^cdmzdw@m7z2y_g+la!o*eocvn^@qevlb-8^)ol0^'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'user',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'test01.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'test01.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
# LANGUAGE_CODE = 'en-us'
# TIME_ZONE = 'UTC'
# 本地化
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
编写视图
- 修改user/views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. 我是Django.")
def index2(request):
return HttpResponse("Hello Django.")
- user目录下新增urls.py文件
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('index2', views.index2, name='index2'),
]
- 修改test01/urls.py文件
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
# path('user/', include('user.urls')), # http://127.0.0.1:8000/user/
# path('index', include('user.urls')), # http://127.0.0.1:8000/index
path('', include('user.urls')), # http://127.0.0.1:8000/
path('admin/', admin.site.urls),
]
- 启动服务
(py_huanjing01) [root@WzcWyt test01]# python manage.py runserver
- 浏览器访问:http://127.0.0.1:8000/
- 浏览器访问:http://127.0.0.1:8000/index2
访问顺序:
浏览器(带着访问路径/index)》test01/urls.py(匹配路径)》user/urls.py(匹配路径)》user/views.py(匹配路径)