franvergara66
franvergara66

Reputation: 10784

Dynamic URLs in Django

I am creating a view that displays the current date and time offset by a certain number of hours. The goal is to design a site for the page /time/plus/1/ displays the date and time in an hour, the page /time/plus/2/ displays the date and time in two hours, the page /time/ plus/3/ displays the date and time in three hours, and so on. This is my function in views.py:

def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "In %s hour(s), it will be %s." % (offset, dt)
    return HttpResponse(html)

and this is the content of my url.py file:

from django.conf.urls import patterns, include, url
from aplicacion1.views import hours_ahead

urlpatterns = patterns('',
    url(r'^time/plus/(d{1,2})/$', hours_ahead),)

The pattern in the views.py should accept only numbers one or two digits Django should display an error "page not found" otherwise. The URL http://127.0.0.1:8000/time/plus/(no hours) should also throw a 404 error. But when I run the server and try to access a URL like http://127.0.0.1:8000/time/plus/24/, tells me the following error:

Page not found (404)
Request Method: GET
Request URL:    

http://127.0.0.1:8000/time/plus/24/
Using the URLconf defined in cibernat.urls, Django tried these URL patterns, in this order:
^$
^time/$
^time/plus\d+/$
^admin/doc/
^admin/
The current URL, time/plus/24/, didn't match any of these.

What is the error I'm making? I see that the regular expression looks correct

Upvotes: 0

Views: 1597

Answers (1)

karthikr
karthikr

Reputation: 99620

Your URL pattern should be

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

You forgot the \ before d

Upvotes: 3

Related Questions