首页 > Web开发 > 详细

django-URL别名的作用

时间:2019-10-24 15:48:47      阅读:90      评论:0      收藏:0      [点我收藏+]

接include函数那一节。

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

基本目录:

技术分享图片

 

 book\urls.py

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

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

<!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后,这里的同样也要更改,较为繁琐。

 

django-URL别名的作用

原文:https://www.cnblogs.com/xiximayou/p/11732611.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!