參考資料
B站網(wǎng)課:點擊藍色字體跳轉
或者復制鏈接在瀏覽器打開:https://www.bilibili.com/video/BV1vK4y1o7jH?p=14&vd_source=597e21cf34ffcdce468ba00be2177e8a
Django應用
創(chuàng)建
終端:
cd django
cd day03
cd mysite3
python3 manage.py startapp music(應用名)
注冊
在settings.py的INSTALLED_APPS中添加應用名即可
分布式路由
news開頭的交由news管理
music開頭的交由music管理
配置分布式路由
Step1 - 主路由中調用include函數(shù)
語法:include(‘app名字.url模塊名’)
作用:用于將當前路由轉到各個應用的路由配置文件的urlpatterns進行分布式處理
Step2 - 應用下配置urls.py
應用下手動創(chuàng)建urls.py文件
內容結構同主路由完全一樣
配置分布式路由的示例
主路由中調用include函數(shù)
http://127.0.0.1:8000/music/index
在urls.py中添加:
path('music/',include('music.urls'))
import某個已有的庫,可以將鼠標放在紅波浪線處 Alt+回車 直接導入
應用下配置urls.py
app-new-pythonfile-urls
#http://127.0.0.1:8000/music/index
應用music的urls.py
from django.urls import path
from . import views
urlpatterns = [
path('index',views.index_view)
]
效果
練習
創(chuàng)建應用news和sport
終端:在django/day03/mysite3下
python3 manage.py startapp news
python3 manage.py startapp sport
在settings.py里進行注冊
urls.py
添加內容:
#http://127.0.0.1:8000/news/index
path('news/',include('news.urls')),
#http://127.0.0.1:8000/sport/index
path('sport/',include('sport.urls'))
news下新建urls.py(sport 同理)
from django.urls import path
from . import views
urlpatterns = [
#http://127.0.0.1:8000/news/index
path('index',views.index_view)
]
news的views.py(sport同理)
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index_view(request):
return HttpResponse('這是新聞頻道首頁')
效果
應用下的模版
應用同名嵌套文件夾——避免找不到應用下的模版
news-右鍵-new-directory-templates-右鍵-new-directory-news-右鍵-new-html-index
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新聞頻道</title>
</head>
<body>
我是新聞頻道首頁
</body>
</html>
news的views.py:
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index_view(request):
return render(request,'news/index.html')
效果:文章來源:http://www.zghlxwxcb.cn/news/detail-825333.html
小結
為了分而治之,引入了應用、分布式路由和應用下的模版。文章來源地址http://www.zghlxwxcb.cn/news/detail-825333.html
到了這里,關于Django后端開發(fā)——Django應用及分布式路由的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!