Making a Regex Django URL Token Optional

Federer picture Federer · Feb 24, 2010 · Viewed 27.3k times · Source

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'),

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Feb 24, 2010
('^(?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.