How to understand the Url patterns for eg. (?P<slug>[-\w]+)/$
in django url.py
Asked
Active
Viewed 2,976 times
-3

Chris Morgan
- 86,207
- 24
- 208
- 215

Gopi Kirupanithi
- 53
- 1
- 7
-
2I was tempted to just recommend the [manual](https://docs.djangoproject.com/en/dev/topics/http/urls/). – Jonas Schäfer Apr 18 '12 at 05:02
-
It's a regular expression. Read up on http://docs.python.org/library/re.html to understand more. – agf Apr 18 '12 at 05:15
4 Answers
4
This url: (?P<slug>[-\w]+)/$
Says that you are passing a variable to your view called slug
could be any digits or letters and -
your view is like this:
def my_view(request, slug):
....
hope it helps...
0

Burhan Khalid
- 169,990
- 18
- 245
- 284
-
2Don't post just links as answers. Either add details / examples or post it as a comment. – agf Apr 18 '12 at 05:15
-
I totally agree with agf even though the question of Gopi was not wise. Regular expressions is a huge field where just a link does not help. – Timo Jun 01 '14 at 05:39
0
Note that slug fields might also include digits (not just letters and the dash), so you want to alter it to say something like:
SLUG = '(?P<slug>[\w\d-]+)'
I hope this helpful to you...

DaveShaw
- 52,123
- 16
- 112
- 141

Thanag Vignesh Raja T
- 13
- 1
- 9
-
This doesn't answer the question. He was asking how to interpret them, not how to change them to do something. – agf Apr 18 '12 at 05:16
0
I think it is not a valid regex pattern. "[-\w]+" will get "word and -", something like "a-b9-c-" or "---" (?P...) is a "Named Group". If you don't give its name, python (mine is 2.7) will raise error.
>>> m = re.match("(?P<e>[-\w]+)/$", "a-b-c-/")
>>> m.group('e')
'a-b-c-'
>>> m = re.match("(?P[-\w]+)/$", "a-b-c-/")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/re.py", line 137, in match
return _compile(pattern, flags).match(string)
File "/usr/lib/python2.7/re.py", line 244, in _compile
raise error, v # invalid expression
sre_constants.error: unknown specifier: ?P[

wuliang
- 749
- 5
- 7
-
But it has the group specified. It *is* valid. (I presume you were looking at the non-escaped version which I fixed three-quarters of an hour before you posted this.) – Chris Morgan Apr 19 '12 at 05:05