8

In the Django urls I need an optional named group. This conf without arguments raised an 404 exception:

r'^list_cv/(?P<category>[\d]+)?/$'

How to make optional named group?

I159
  • 29,741
  • 31
  • 97
  • 132
  • 1
    possible duplicate of [Making a Regex Django URL Token Optional](http://stackoverflow.com/questions/2325433/making-a-regex-django-url-token-optional) – Bartek Nov 25 '11 at 14:29

3 Answers3

8

Works this way to me:

r'^list_cv/(?:(?P<category>[\w+])/)?$'

EDIT:

Comparing to the original answer the difference is in the repetition match.

(?:(?P<category>[\w+])/)?$ vs original (?:(?P<category>[\w+])?/)$.

I159
  • 29,741
  • 31
  • 97
  • 132
4

The last slash should be part of the optional RE, and the RE should be like

r'^list_cv/(?:(?P<category>[\w+])?/)$'

I didn't test it, though.

Mohammad Tayseer
  • 509
  • 1
  • 5
  • 10
  • 2
    This was not really working, but the third answers was working http://stackoverflow.com/a/8271065/548558 with this r'^list_cv/(?:(?P[\w+])/)?$' – Azd325 Mar 21 '12 at 14:49
4

I find that it's more legible to create a separate url pattern for the url without the named group.

url(r'^list_cv/$', my_view),
url(r'^list_cv/(?P<category>[\d]+)/$', my_view),
Alasdair
  • 298,606
  • 55
  • 578
  • 516