0

I'm trying set an offset but I want to limit it to a maximum of 99 hours by only allowing either one- or two-digit numbers but I'm not sure of the syntax to use with Django 2.0. I've tried to look for updated documentation but I can't find it, maybe I missed it but I did look before posting here.

Here is the code in my views.py file:

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

Here is the code from my urls.py file, this allows me to pass an integer but I want to limit this to 1- or 2- digit numbers only:

path('date_and_time/plus/<int:offset>/', hours_ahead),

I've tried

path(r'^date_and_time/plus/\d{1,2}/$', hours_ahead),

but I get the Page not found (404) error.

Thanks in advance!

Ceginner
  • 29
  • 1
  • 5

1 Answers1

2

path in Django 2.0+ doesn't accept regular expressions. You'll either have to use re_path:

from django.urls import re_path

...

re_path(r'^date_and_time/plus/\d{1,2}/$', hours_ahead),

Or perform the validation in your view:

def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()

    if not 0 <= offset <= 99:
        raise Http404()

I don't like complicated regular expressions, so I would keep the new-style route format and perform the validation in the view itself.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • An alternative is to write a custom [path converter](https://docs.djangoproject.com/en/2.0/topics/http/urls/#registering-custom-path-converters) and use it instead of `int` in the `path` call. – Daniel Roseman Jan 23 '18 at 18:07