Django 2.0 URL 正则表达式
Django 2.0 URL regular expressions
我正在尝试设置一个偏移量,但我想通过仅允许一位或两位数字来将其限制为最多 99 小时,但我不确定用于 Django 2.0 的语法。我试图寻找更新的文档,但我找不到它,也许我错过了,但我在发帖前确实看过了。
这是我的 views.py 文件中的代码:
# Creating a view for showing current datetime + and offset of x amount of hrs
def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
# Throws an error if the offset contains anything other than an integer
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
return HttpResponse(html)
这是我的 urls.py 文件中的代码,这允许我传递一个整数,但我想将其限制为仅 1 位或 2 位数字:
path('date_and_time/plus/<int:offset>/', hours_ahead),
我试过了
path(r'^date_and_time/plus/\d{1,2}/$', hours_ahead),
但我收到页面未找到 (404) 错误。
提前致谢!
path
在 Django 2.0+ 中不接受正则表达式。您要么必须使用 re_path
:
from django.urls import re_path
...
re_path(r'^date_and_time/plus/\d{1,2}/$', hours_ahead),
或在您的视图中执行验证:
def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
if not 0 <= offset <= 99:
raise Http404()
我不喜欢复杂的正则表达式,所以我会保留新式路由格式并在视图本身中执行验证。
我正在尝试设置一个偏移量,但我想通过仅允许一位或两位数字来将其限制为最多 99 小时,但我不确定用于 Django 2.0 的语法。我试图寻找更新的文档,但我找不到它,也许我错过了,但我在发帖前确实看过了。
这是我的 views.py 文件中的代码:
# Creating a view for showing current datetime + and offset of x amount of hrs
def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
# Throws an error if the offset contains anything other than an integer
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
return HttpResponse(html)
这是我的 urls.py 文件中的代码,这允许我传递一个整数,但我想将其限制为仅 1 位或 2 位数字:
path('date_and_time/plus/<int:offset>/', hours_ahead),
我试过了
path(r'^date_and_time/plus/\d{1,2}/$', hours_ahead),
但我收到页面未找到 (404) 错误。
提前致谢!
path
在 Django 2.0+ 中不接受正则表达式。您要么必须使用 re_path
:
from django.urls import re_path
...
re_path(r'^date_and_time/plus/\d{1,2}/$', hours_ahead),
或在您的视图中执行验证:
def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
if not 0 <= offset <= 99:
raise Http404()
我不喜欢复杂的正则表达式,所以我会保留新式路由格式并在视图本身中执行验证。