Possible error at usage of reverse URL in templates.

19 views
Skip to first unread message

Sebastian Piskorski

unread,
Jun 20, 2014, 1:44:57 PM6/20/14
to django...@googlegroups.com
I'd like to make sure that this is an error not the feature.

I use following code in template

<li><a href="{% url 'player-select' player.id %}">{{ player.id }} : "{{ player.name}}"</a></li>

And in urls.py everything goes fine with those rules:

1. url(r'^player/select/(?P<playerId>\d+)/$', myapp.views.player.select, name="player-select"),
result URL is: /player/select/1/

or:

2. url(r'^player/select/(?P<playerId>\d+)/?$', myapp.views.player.select, name="player-select"),
result URL is: /player/select/1

or:

3. url(r'^player/select/(?P<playerId>\d+)?/?$', myapp.views.player.select, name="player-select"),
result URL is: /player/select/1

but with this rule I get error:

4. url(r'^player/select/((?P<playerId>\d+)/)?$', neuroapp.views.player.select, name="player-select"),
error message:
Reverse for 'player-select' with arguments '(1L,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['player/select/((?P<playerId>\\d+)/)?#39;]

for me 4th pattern is pretty much the same as 3rd, but Django has other opinion. If you can, please explain me why.


Russell Keith-Magee

unread,
Jun 22, 2014, 7:26:42 PM6/22/14
to Django Users
Hi Sebastian,

There is a very significant difference between the third pattern and the last - the extra set of braces. That extra set of braces means that the regex group that is being matched is 

(?P<playerId>\d+)/

That is - one or more numerical digits, identified as playerId, that *must* be followed by a slash. 

Complicating matters, that entire group is marked as optional, so the "number plus slash" group is optional on the URL.

As a result,

/player/select/

and

/player/select/1/

should match the pattern, but 

/player/select/1

will not (because it doesn't end with a slash).

In contrast, pattern 3 is trying to match: 

(?P<playerId>\d+)?/?

That is - one or more numerical digits, which is an optional construct, optionally followed by a slash. This should find a match with:

/player/select/1/
/player/select/1
/player/select//
/player/select/

I hope that helps.

Yours,
Russ Magee %-)


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/35dfc988-f234-42a0-8ded-cbacd84e6c55%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages