【Django模板】<a>标签中 url 使用详解( url 跳转到指定页面)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33867131/article/details/81949022

1、主urls.py文件配置如下:

from django.urls import path
from django.conf.urls import include

from myblog import views
urlpatterns = [

    path('', views.index), 
    path('myblog/', include('myblog.urls')),
]

2、APP的urls.py文件配置如下:

from django.urls import path
from myblog import views

urlpatterns = [

    path('', views.index), 

    path('login/', views.login, name='login'),  # 这里设置name,为了在模板文件中,写name,就能找到这个路由
    path('book/', views.book, name='book'),
    path('movie/', views.movie, name='movie'),
    path('book/detail/<book_id>/<catgray>/', views.book_detail, name='detail'),

]

3、APP的views.py文件如下:

from distutils.command import register

from django.shortcuts import render, reverse, redirect
from django.http import HttpResponse


def index(request):
    return render(request, 'index.html', {'articles': 18})

def login(request):
    return HttpResponse("注册页面")

def book(request):
    return HttpResponse("读书页面")


def movie(request):
    return HttpResponse("电影页面")


def book_detail(request, book_id, catgray):
    text = '文章详情页,该文章ID是:%s,分类是:%s' % (book_id, catgray)
    return HttpResponse(text)

4、index.html文件如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<ul>
    <li><a href="/">首页</a></li>

    <li><a href="{% url 'login' %}?next=asd/ ">登录</a></li>
    # 点读书就会调到,读书页,路径
    <li><a href="{% url 'book' %}">读书</a></li>
    # 在这里,直接写name,就能找到urls文件中对应的路由
    <li><a href="{% url 'book' %}">读书</a></li>

    <li><a href="{% url 'movie' %}">电影</a></li>

    <li><a href="{% url 'detail' book_id='1' catgray=2 %}">最火的一篇文章</a></li>
</ul>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_33867131/article/details/81949022