Django-url的反向解析
反向解析:
-- 使用path动态名称来查找相应的路由、而不用考虑什么相对路径和绝对路径
在模板中使用url的别名:
1、views.py
-----------------------------
from django.http import HttpResponse
from django.shortcuts import render
#模板中传参
def test_var(request, var):
print(var)
return HttpResponse('test_var 模板中传参')
--------------------------------------------------------------
2、urls.py
----------------------------------------------------------------------------------
from django.contrib import admin
from django.urls import path
from url_app.views import *
urlpatterns = [
path('test_url_result/', test_url_result, name='test_result'), #http://127.0.0.1:8000/test_url_result
# <int:var> 从模板中传参 - var 为变量名-views.py中test_var函数的变量名
path('testvar/<int:var>', test_var, name='test_var'), #<int:id> 从模板中传参
]
--------------------------------------------------------------------------------
3、模板中-test.html
-------------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试url</title>
</head>
<body>
<!--反向解析-->
<!--url 'url的别名' 这里只认url别名,不认url地址-->
<a href="{% url 'test_result' %}">url 反向解析</a>
<a href="{% url 'test_var' '1' %}">url 反向解析带参数</a>
</body>
</html>
---------------------------------------------------------
views.py
-----------------------------------------------------
def test_url_result(request):
#状态码为302的就是跳转
from django.urls import reverse
url = reverse('base_index') #跳转到urls.py中 path 的别名为:base_index 的路由
return HttpResponseRedirect(url) #跳转
--------------------------------------------------------------
urls.py
----------------------------------------------------------
from django.contrib import admin
from django.urls import path
from url_app.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('test/url', test_url, name='base_index'), #http://127.0.0.1:8000/test/url
]
-------------------------------------------------------------------------------