How to pass an optional argument to url in Django

django, django-urls

Solution

You can create two URL patterns, one with a default parameter to 1 and the other with the `page` matching in the URL:

# urls.py :
url(r'^page$', MyIndexView.as_view(), {'page': 1}, name='index'),
url(r'^page/(?P<page>\w+)$', MyIndexView.as_view(), name='index'),

The third argument of the `url` function is `kwargs`, hence `kwargs['page']` will be 1 in the first case and defined by the URL in the second.

Problem

I have an url pattern with one optional parameter: ``` # urls.py : url(r'^(page/(?P<page>\w+))?$', MyIndexView.as_view(), name='index'), ``` Pagination and everything else works well, until I create an url to a specific page in my template: ``` # templates/mysite.html {% url 'index' 54 %} ``` Then I get an error: ``` Reverse for 'index' with arguments '(54,)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'(page/(?P<page>\\w+))?$'] ``` Without the parameter it works: ``` {% url 'index' %} ``` I also tried: ``` {% url 'index' page=54 %} ``` and got similar error.

Original source

Related problems