Optional Python named groups

In Django urls, I need an extra named group. This conf with no arguments raised exception 404:

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

How to make an optional named group?

+6
source share
3 answers

To be true, it works like this:

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

I find it more legible to create a separate url pattern for a URL without a named group.

 url(r'^list_cv/$', my_view), url(r'^list_cv/(?P<category>[\d]+)/$', my_view), 
+3
source

The last slash must be part of an optional RE, and RE must be like

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

I have not tested this.

+2
source

Source: https://habr.com/ru/post/902397/


All Articles