url反向解析小例子

test4/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('booktest.urls', namespace='booktest'))
]

booktest/urls.py

from django.urls import path, re_path
from booktest import views

app_name = 'booktest'
urlpatterns = [
    path('', views.index, name='index'),
    re_path(r'^(\d+)$', views.show, name='show')

]

views.py

from django.shortcuts import render
from booktest.models import *


def index(request):
    # 查询一个
    # hero = HeroInfo.objects.get(pk=35)
    # context = {'hero': hero}
    # 查询列表(多个)
    list = HeroInfo.objects.all()
    # list = HeroInfo.objects.filter(isDelete=True)
    context = {'list': list}
    return render(request, 'booktest/index.html', context)


def show(request, id):
    context = {'id': id}
    return render(request, 'booktest/show.html', context)

show.html

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

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{# <a href="123">显示</a>  #}
<a href="{% url 'booktest:show' 123 %}">显示</a>
<hr>
{# {{ hero.showname }} #}
{% for item in list %}
    {{ forloop.counter }} :{{ item.hname }}  {# forloop.counter得到循环的第几次 #}
    <hr>
    {% empty %}
    您查询的数据不存在!
{% endfor %}
</body>
</html>
  • url:反向解析
{ % url 'name' p1 p2 %}

{% url 'booktest:show' 123 %}  其中booktest是test4/urls.py/namespace中的内容,
                    show是booktest/urls.py/name中的内容,
                    123是(\d+)需要传递的参数的内容


解释一下页面跳转:
index.html 中如果有  <a href="123">显示</a>
href中123地址。先到test4中匹配空即127.0.0.1:8000
因为有
include('booktest.urls', namespace='booktest')跳转到booktest.urls中
re_path(r'^(\d+)$', views.show, name='show')与(\d+)进行匹配即127.0.0.1:8000/123
再到views.py中找到show函数。
return render(request, 'booktest/show.html', context)跳转到show.html页面显示id

猜你喜欢

转载自www.cnblogs.com/gaota1996/p/10441967.html