47

You have a URL which accepts a first_name and last_name in Django:

('^(?P<first_name>[a-zA-Z]+)/(?P<last_name>[a-zA-Z]+)/$','some_method'),

How would you include the OPTIONAL URL token of title, without creating any new lines. What I mean by this is, in an ideal scenario:

#A regex constant
OP_REGEX = r'THIS IS OPTIONAL<title>[a-z]'
#Ideal URL
('^(?P<first_name>[a-zA-Z]+)/(?P<last_name>[a-zA-Z]+)/OP_REGEX/$','some_method'),

Is this possible without creating a new line i.e.

('^(?P<first_name>[a-zA-Z]+)/(?P<last_name>[a-zA-Z]+)/(?P<title>[a-zA-Z]+)/$','some_method'),
Federer
  • 33,677
  • 39
  • 93
  • 121

2 Answers2

84
('^(?P<first_name>[a-zA-Z]+)/(?P<last_name>[a-zA-Z]+)(?:/(?P<title>[a-zA-Z]+))?/$','some_method'),

Don't forget to give title a default value in the view.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    thanks for that. How would I make a URL of JUST optional '`titles`'? i.e. `(?:/(?P[a-zA-Z]+))?(?:/(?P[a-zA-Z]+))?` thanks for any help – Federer Feb 24 '10 at 15:19
  • 7
    Note that the ?: is important in the outer group. Without it, the URL will work properly when navigated to, but reverse() won't notice the argument inside. – Chris Jan 28 '13 at 19:56
  • More info about this in the [official docs](https://docs.djangoproject.com/en/1.10/topics/http/urls/#nested-arguments). – srus Feb 20 '17 at 16:12
1

In case your are looking for multiple optional arguments, without any required ones, just omit "/" at the beginning, such as:

re_path(r'^view(?:/(?P<dummy1>[a-zA-Z]+))?(?:/(?P<dummy2>[a-zA-Z]+))?(?:/(?P<dummy3>[a-zA-Z]+))?/$', views.MyView.as_view(), name='myname'),

which you can browse at:

http://localhost:8000/view/?dummy1=value1&dummy2=value2&dummy3=value3
Rexcirus
  • 2,459
  • 3
  • 22
  • 42