django2.0 url参数


# url.py

from django.urls import path, re_path
from . import views
urlpatterns = [
# 配置简单URL
path('', views.index),

# 带变量的URL
# path('<year>/<int:month>/<slug:day>', views.mydate),
re_path('(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2}).html', views.mydate),

# 带参数name的URL,给url命名
re_path('(?P<year>[0-9]{4}).html', views.myyear, name='myyear'),

# 参数为字典的URL
re_path('dict/(?P<year>[0-9]{4}).htm', views.myyear_dict, {'month': '05'}, name='myyear_dict')
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# views.py

from django.shortcuts import render
from django.http import HttpResponse


def index(request):
return HttpResponse("Hello world")

# 带变量的URL的视图函数
def mydate(request, year, month, day):
return HttpResponse(str(year) +'/'+ str(month) +'/'+ str(day))

# 参数name的URL的视图函数
def myyear(request, year):
return render(request, 'myyear.html')

# 参数为字典的URL的视图函数
def myyear_dict(request, year, month):
return render(request, 'myyear_dict.html',{'month':month})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"""
<year> <str:year> 字符串类型,变量为year
<int:month> 整型,变量为month
<slug:day> 变量为day,格式为slug,ASCII字符 _ - 组成
<uuid:ukey> uuid格式的对象 ,数字 小写字母 - 组成

(?P<year>[0-9]{4})

?P 固定格式
<变量名>编写规则
[0-9]{4} 正则,长度4,取值在0-9
"""
————————————————
版权声明:本文为CSDN博主「vtenten」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sunt2018/article/details/87928404

posted @ 2021-04-10 21:32  天涯海角路  阅读(3)  评论(0)    收藏  举报