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)}")
相关推荐
AC赳赳老秦1 天前
Windows 系统 OpenClaw 执行策略报错及管理员权限设置深度解析与实操指南
运维·人工智能·python·django·自动化·媒体·openclaw
vx_biyesheji00012 天前
计算机毕业设计:Python汽车市场智能决策系统 Flask框架 可视化 机器学习 AI 大模型 大数据(建议收藏)✅
大数据·人工智能·python·算法·django·汽车·课程设计
橘子编程2 天前
Django全栈开发终极指南
后端·python·django·npm·html·pandas·html5
小陈工3 天前
Python Web开发入门(八):用户认证系统实现,给你的应用加上安全锁
开发语言·前端·数据库·python·安全·django·sqlite
北冥有羽Victoria3 天前
Django 实战:SQLite 转 MySQL 与 Bootstrap 集成
大数据·服务器·python·django·编辑器
huabiangaozhi3 天前
vscode配置django环境并创建django项目(全图文操作)
vscode·django·sqlite
湛生4 天前
django学习
数据库·后端·python·django·sqlite
2601_949817724 天前
使用Django Rest Framework构建API
数据库·django·sqlite
寰宇的行者4 天前
深入理解 Django 异步视图中的 `sync_to_async` 与协程
数据库·django
源码之屋4 天前
计算机毕业设计:新能源汽车多维度数据分析系统 Django框架 Scrapy爬虫 可视化 数据分析 大数据 大模型 机器学习(建议收藏)✅
大数据·python·scrapy·django·汽车·课程设计·美食