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)}")
相关推荐
z***565624 分钟前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
linuxxx1103 小时前
高考志愿填报辅助系统
redis·后端·python·mysql·ai·django·高考
qq_22589174667 小时前
基于Python+Django餐饮评论大数据分析与智能推荐系统 毕业论文
开发语言·后端·python·信息可视化·数据分析·django
chushiyunen9 小时前
django使用笔记
笔记·python·django
o***36939 小时前
【玩转全栈】----Django基本配置和介绍
数据库·django·sqlite
A尘埃13 小时前
Python后端框架:FastAPI+Django+Flask
python·django·flask·fastapi
m0_595199851 天前
Django Rest Framework 和 JWT 身份验证
后端·python·django
m***56721 天前
【玩转全栈】----Django制作部门管理页面
后端·python·django
墨客希1 天前
Django 学习指南
数据库·django·sqlite
e***58231 天前
使用Django Rest Framework构建API
数据库·django·sqlite