Django后端开发——Django应用及分布式路由


参考资料

B站网课:点击蓝色字体跳转
或者复制链接在浏览器打开:https://www.bilibili.com/video/BV1vK4y1o7jH?p=14&vd_source=597e21cf34ffcdce468ba00be2177e8a


Django应用

创建

终端:

cd django
cd day03
cd mysite3
python3 manage.py startapp music(应用名)

注册

在settings.py的INSTALLED_APPS中添加应用名即可
在这里插入图片描述

分布式路由

在这里插入图片描述
news开头的交由news管理
music开头的交由music管理

配置分布式路由

Step1 - 主路由中调用include函数

语法:include(‘app名字.url模块名’)
作用:用于将当前路由转到各个应用的路由配置文件的urlpatterns进行分布式处理

在这里插入图片描述

Step2 - 应用下配置urls.py

应用下手动创建urls.py文件
内容结构同主路由完全一样
在这里插入图片描述

配置分布式路由的示例

主路由中调用include函数

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)
]

效果

在这里插入图片描述

练习

在这里插入图片描述

创建应用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')

效果:
在这里插入图片描述

小结

为了分而治之,引入了应用、分布式路由和应用下的模版。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

^_^2412

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值