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)}")
相关推荐
noravinsc6 小时前
django 一个表中包括id和parentid,如何通过parentid找到全部父爷id
python·django·sqlite
LuckyLay9 小时前
1.1.1数据类型与变量——AI教你学Django
数据库·django·sqlite
51712 小时前
Django中序列化与反序列化
后端·python·django
Q_Q51100828517 小时前
python的保险业务管理与数据分析系统
开发语言·spring boot·python·django·flask·node.js·php
打酱油的;1 天前
爬虫-request处理get
爬虫·python·django
PythonicCC1 天前
Django核心知识点详解:JSON、AJAX、Cookie、Session与用户认证
ajax·django·json
小王子10241 天前
Django+DRF 实战:自定义异常处理流程
后端·django·web开发
程序设计实验室2 天前
在 django-ninja 中实现类似腾讯阿里云的应用鉴权机制
django·djangostarter
开开心心_Every2 天前
全能视频处理工具介绍说明
开发语言·人工智能·django·pdf·flask·c#·音视频