2

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.

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
dev9
  • 2,202
  • 4
  • 20
  • 29
  • Its a bit of creepy to use optional arguments. There might be issues related to tailing `/` of URL etc. I'd suggest you to not use it.. – Surya Jun 05 '14 at 17:22

1 Answers1

8

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.

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
  • Even without this, it works well. The error appear only when I try to use `{% url ... %}` – dev9 May 20 '14 at 08:09
  • Indeed... I have always used two patterns for this kind of case and it seems to be a convention: http://stackoverflow.com/questions/1352834/optional-get-parameters-in-django I don't really see why it is not matching your URL for your pattern (maybe just a typo I don't see right now) but I leave my answer as a working alternative ;) – Maxime Lorant May 20 '14 at 08:15
  • Well, adding second pattern haven't changed anything. It still works unitl I use `{% url ... %}` – dev9 May 20 '14 at 08:39
  • @MaximeLorant you need to use a different name in the second url pattern – Leonardo.Z May 20 '14 at 08:46