-3

How to understand the Url patterns for eg. (?P<slug>[-\w]+)/$ in django url.py

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

4 Answers4

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...

olofom
  • 6,233
  • 11
  • 37
  • 50
pahko
  • 2,580
  • 4
  • 22
  • 25
0

First Mastering Regular Expressions, then 7.2.1 - Regular Expression Syntax

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • 2
    Don'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
  • 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