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!
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.