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)}")
相关推荐
小王同学66662 天前
Django 5 中实现文件上传功能
数据库·django·sqlite
vx-程序开发2 天前
【java项目分享】springboot农产品销售平台14952
java·javascript·spring boot·python·eclipse·django·php
qq_22589174663 天前
基于Python的外卖订单数据分析可视化系统
python·信息可视化·django
酩酊仙人3 天前
Windows Server部署django
windows·django·sqlite
倒流时光三十年4 天前
第三阶段 26 · highlight 高亮(返回命中片段)
后端·python·django
黑桃小柒74 天前
Django模型关系:从一对多到多对多全解析
数据库·django·sqlite
Python私教4 天前
Django + AI 做智能工单系统:自动分类、重复合并、服务时限与人工审批实战
人工智能·python·django