【问题标题】:Django 2.0 URL regular expressionsDjango 2.0 URL 正则表达式
【发布时间】:2018-01-23 17:43:30
【问题描述】:

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

提前致谢!

【问题讨论】:

    标签: python django django-2.0


    【解决方案1】:

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

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

    【讨论】:

    • 另一种方法是编写自定义path converter 并在path 调用中使用它而不是int。
    猜你喜欢
    • 2018-12-09
    • 2011-03-22
    • 2013-07-26
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多