Djang学习- URL反转

代码中url书写规范:

url反向解析

urls:

python 复制代码
path('test/url', views.test_url),
    path('test_result/<int:age>', views.test_result, name="rl")

views:

python 复制代码
def test_url(request):
    return render(request, 'test_url.html')


def test_result(request,age):
    return HttpResponse("--test----result---")

templates:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="http://127.0.0.1:8000/test_result">绝对地址</a>
<a href="/test_result">带'/'的相对地址</a>
<a href="test_result">不带'/'的相对地址</a>
<a href="{% url 'rl' '100'%}">反向解析跳转</a>
</body>
</html>
python 复制代码
def test_result(request,age):
    # 302 重定向
    from django.urls import reverse
    from django.http import HttpResponseRedirect
    from django.shortcuts import redirect
    url = reverse('base',args=[10])
    return redirect(url)

可以使用HttpResponseRedirect和redirect进行重定向,不能直接使用HttpResponse,HttpResponse会直接输出你要重定向的url,而不是去重定向

复制代码
相关推荐
冬夜戏雪6 小时前
实习面经摘录(九)
学习
arvin_xiaoting6 小时前
OpenClaw学习总结_I_核心架构_8:SessionPruning详解
前端·chrome·学习·系统架构·ai agent·openclaw·sessionpruning
妄汐霜8 小时前
小白学习笔记(spring框架的aop和tx)
笔记·学习
椎49510 小时前
JSONUtil工具包大致学习使用
学习
leiming611 小时前
CAN 通信协议学习讲义(带图文 + C 语言代码)
c语言·开发语言·学习
星空12 小时前
RAG学习第一节
学习
知识分享小能手12 小时前
MongoDB入门学习教程,从入门到精通,MongoDB入门指南 —— 知识点详解(2)
数据库·学习·mongodb
炽烈小老头12 小时前
【 每天学习一点算法 2026/03/24】寻找峰值
学习·算法
Nan_Shu_61412 小时前
学习:Cesium (3)
学习
C羊驼14 小时前
C语言学习笔记(十五):预处理
c语言·经验分享·笔记·学习·算法