0

我正在尝试设置偏移量,但我想通过只允许一位或两位数字将其限制为最多 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) 错误。

提前致谢!

4

1 回答 1

2

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()

我不喜欢复杂的正则表达式,所以我会保留新样式的路由格式并在视图本身中执行验证。

于 2018-01-23T17:48:58.360 回答