VicenteC
VicenteC

Reputation: 422

Omited parameters in a url

In the book: 'The Django's book 2.0' the author talk about using 'catchers' in the url. According to him, you can omit some parameter in the url and define it in the views.py in order to prevent an error 404:

urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hours/(?P<hour>\d+)/$', views.date_in),

views.py

def date_in(request, hour='02'): #Default argument defined here
    hour=int(hour)
    #some extra code

This doesn't work for me. I still get the error 404 because the argument after hours doesn't exist.

Upvotes: 1

Views: 39

Answers (1)

Selcuk
Selcuk

Reputation: 59184

You did not omit the hour argument in your urls.py. Try this:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hours/(?P<hour>\d+)/$', views.date_in),
    url(r'^hours/$', views.date_in),

This will create two routes for the same view. One that accepts a hour argument, and one that does not. The one without the hour argument will use the default value ('02').

Upvotes: 2

Related Questions