Django 解析路由参数

编写带url参数的路由,4种类型参数

app1.url.py

复制代码
from django.urls import path
from . import views

urlpatterns = [
    path('index', views.index, name='index'),
    path('test', views.test, name='test'),
    path('test_int/<int:id>/', views.test_int, name='test_int'),
    path('test_str/<str:strdata>/', views.test_str, name='test_str'),
    path('test_slug/<slug:slugdata>/', views.test_slug, name='test_slug'),
    path('book_uuid/<uuid:bookuuid>/', views.book_uuid, name='book_uuid'),
]

app1.views.py

复制代码
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
    return HttpResponse("app1 的index")

def test(request):
    return render(request, '1/index.html', {})

def test_int(request, id):
    # 你可以在这里使用 'id',比如从数据库获取对应的数据
    # ...
    response = HttpResponse(f"test_int路由访问参数:{id}")
    response['Content-Type'] = "text/html; charset=utf-8"
    return response

def test_str(request, strdata):
    # 你可以在这里使用 'id',比如从数据库获取对应的数据
    # ...
    response = HttpResponse(f"test_str路由访问参数:{strdata}")
    response['Content-Type'] = "text/html; charset=utf-8"
    return response

def test_slug(request, slugdata):
    # 你可以在这里使用 'id',比如从数据库获取对应的数据
    # ...
    response = HttpResponse(f"test_slug路由访问参数:{slugdata}")
    response['Content-Type'] = "text/html; charset=utf-8"
    return response

from uuid import UUID

def book_uuid(request, bookuuid: UUID):
    # 在这里,'bookuuid' 是一个UUID 对象。
    return HttpResponse(f"Book's UUID is: {str(bookuuid)}")
相关推荐
二等饼干~za89866835 分钟前
GEO 源码部署搭建详细操作教程(2026 最新版)
线性代数·django·开源·音视频·ai-native
源码之家3 小时前
计算机毕业设计:Python农业数据分析与粮食产量预测系统 Django框架 数据分析 可视化 机器学习 深度学习 大数据 大模型(建议收藏)✅
python·机器学习·信息可视化·数据分析·django·flask·课程设计
ILYT NCTR3 小时前
vscode配置django环境并创建django项目(全图文操作)
vscode·django·sqlite
菜鸟学Python12 小时前
Python生态在悄悄改变:FastAPI全面反超,Django和Flask还行吗?
开发语言·python·django·flask·fastapi
天选之子12321 小时前
Django基本概念入门(一)
python·django·sqlite
源码之家1 天前
计算机毕业设计:Python棉花产业数据可视化与预测系统 Django框架 ARIMA算法 数据分析 可视化 爬虫 大数据 大模型(建议收藏)✅
人工智能·python·算法·信息可视化·数据挖掘·django·课程设计
源码之家1 天前
计算机毕业设计:Python农产品智能推荐与可视化分析系统 Flask框架 矩阵分解 数据分析 可视化 协同过滤推荐算法 深度学习(建议收藏)✅
python·矩阵·数据挖掘·数据分析·django·flask·课程设计
Betelgeuse761 天前
打通 Django 认证:原生 Auth 组件实战与 API 改造
后端·python·django
青花瓷1 天前
PyCharm中创建Django基础网站
ide·pycharm·django
天选之子1231 天前
Django模板(二)
数据库·django·sqlite