python全栈,  后端开发

django 捕获url参数

通过re_path 代替url 的正则

urls.py

from django.contrib import admin
from django.urls import path, re_path
from djapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    # 捕获位置参数
    re_path(r'^showarg(\d+)$', views.show_arg),# 这里会将(\d+)捕获为一个组,作为一个参数传给show_arg函数
    # 捕获关键字参数
    re_path(r'^showarg(?P<num>\d+)$', views.show_arg) # 这里的num参数要和show_arg 定义的参数要一致
]

views.py

def show_arg(request, num):
    return HttpResponse(num)

file

留言

您的电子邮箱地址不会被公开。 必填项已用*标注

闽ICP备20008591号-1