Adjacent strings are concatenated, so you can do something like this:
url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/'
r'(?P<second_slug>[-\w]+?)/'
r'(?P<third_slug>[-\w]+?).html/$',
'apps.Discussion.views.pricing',)
Question
I have a long url pattern in Django similar to this:
url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/(?P<second_slug>[-\w]+?)/(?P<third_slug>[-\w]+?).html/$',
'apps.Discussion.views.pricing',
Definitely it doesn't follow PEP8 guide as the characters are more than 80 in a single line. I have found two approach of solving this:
The first one (using backslash):
url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/(?P<second_slug>[-\w]+?)'\
'/(?P<third_slug>[-\w]+?).html/$',
'apps.Discussion.views.pricing',
The second one - using ():
url((r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/(?P<second_slug>[-\w]+?)',
r'/(?P<third_slug>[-\w]+?).html/$'),
'apps.Discussion.views.pricing'),
Both of them break by Regex. Is there a better approach to solve this issue. OR Is it a bad practice to write such long Regex for urls.
Solution
Adjacent strings are concatenated, so you can do something like this:
url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/'
r'(?P<second_slug>[-\w]+?)/'
r'(?P<third_slug>[-\w]+?).html/$',
'apps.Discussion.views.pricing',)
OTHER TIPS
PEP8 has no regex formatting tips. But try these:
(?i) → re.IGNORECASE
)
slugs = re.compile(r'''
^
top-dir/
(?P<first_slug>[-\w]+?)/
(?P<second_slug>[-\w]+?)/
(?P<third_slug>[-\w]+?).html/
$
''', re.VERBOSE|re.IGNORECASE)
url(slugs, 'apps.Discussion.views.pricing', ...)