前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >django-URL别名的作用(六)

django-URL别名的作用(六)

作者头像
西西嘛呦
发布2020-08-26 10:21:31
6420
发布2020-08-26 10:21:31
举报

接include函数那一节。

作用:为url地址取一个名称,这样在html中引用的时候,无论后台url怎么变,都可以访问到对应的界面,可以减少更改的次数。

基本目录:

book\urls.py

代码语言:javascript
复制
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index,name='index'),
    path('news/', views.news,name='news'),
    path('videos/', views.videos,name='videos'),
]

book\views.py

代码语言:javascript
复制
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    return render(request,'index.html')

def news(request):
    return HttpResponse('我是新闻的首页页面')

def videos(request):
    return HttpResponse('我是视频的首页页面')

book\templates\index.html

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        p{font-size: 28px;}
    </style>
</head>
<body>
<p><a href={% url 'index'%}>index</a></p>
<p><a href={% url 'news'%}>news</a></p>
<p><a href={% url 'videos'%}>videos</a></p>
</body>
</html>

当我们启动服务器后,会首先调用book\views.py中的index函数,跳转到index.html

点击news

点击videos

如果我们不取名字,那么在html中要用"http://localhost:8000/videos",这样虽然也有相同的作用,但是更改urls里面的path后,这里的同样也要更改,较为繁琐。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档