step1:新建一个工作目录WorkSpace/website
step2:在website目录下创建Django项目salviaFlora
django-adminstartproject salviaFlora
当前目录结构
.
├──manage.py
└──salviaFlora
├──asgi.py
├──__init__.py
├── settings.py #网站整体的配置文件
├── urls.py #网站整体的路由映射表
└──wsgi.py
step3:创建一个App,并将该App放到apps文件夹里面,notes:apps与salviaFlora处于同级目录
mkdirapps
mkdirapps/salviaInfo
pythonmanage.py startapp salviaInfo ./apps/salviaInfo
创建完成后网站的目录结构如下
.
├──apps
│ └──salviaInfo
│ ├──admin.py
│ ├──apps.py
│ ├──__init__.py
│ ├──migrations
│ │ └──__init__.py
│ ├──models.py
│ ├──tests.py
│ └──views.py
├──manage.py
└──salviaFlora
├──asgi.py
├──__init__.py
├──__pycache__
│ ├──__init__.cpython-37.pyc
│ └──settings.cpython-37.pyc
├──settings.py
├──urls.py
└──wsgi.py
step4:配置salviaInfo/setting.py文件
import os
import sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,os.path.join(BASE_DIR,'apps'))#将apps文件夹加入到pythonpath中,以被python识别该目录下的app
ALLOWED_HOSTS = ['*',]#允许通过外网ip访问
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'salviaInfo',#注册salviaInfo
]
step5:配置路由映射表salviaFlora/urls.py
输入https://www.salviaflora.com/index/后django送到后台的只有index/这个字符串,然后与path()第一个参数匹配,匹配成功后送到下一级路由映射表include()
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('salviaInfo.urls'))#拿到index/后,匹配成功,然后送到salviaInfo的路由映射表.(''与任何字符串都能匹配成功)
]
step6:进入apps/salviaInfo,配置views.py文件
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse('hello')
step7:在该目录下创建urls.py,并做如下配置
from django.urls import path
from . import views
urlpatterns = [
path('index/',views.index,name='index')#index/经过上一级的路由映射,送到此处,index/会与path()的第一个参数匹配,匹配成功,然后返回该app的views.index
]
step8:启动项目
python manage.py runserver 0:8080
0是0.0.0.0的缩写,允许任何ip访问