| |
Django developers |
On the plane from London to Chicago yesterday, I implemented something I've attached a new urlresolvers.py to this e-mail. It's intended to Given a view name (e.g. 'myproject.polls.views.poll_detail', as a The method is reverse() on both the RegexURLPattern and Here's an example of how it works. Given this root URLconf: urlpatterns = patterns('', Here's how to use it: Ideally there'd be a template-tag interface to this. Something like: {% link 'path.to.month_view' 2005 'apr' %} It's implemented by analyzing the regular expression, which was quite Thoughts? Adrian --
that's been discussed on this list lately -- "reverse" URL creation.
replace the one in django/core, and it works with magic-removal only.
(To use it with trunk, just replace the import line at the top to
import Http404 from django.core.exceptions instead of django.http.)
I've also attached unit tests.
string) and any number of positional or keyword arguments, this code
generates the URL according to the first URL pattern in your URLconf
that matches.
RegexURLResolver classes.
(r'^foo/$', 'path.to.foo_view'),
(r'^dates/(\d{4})/(\w{3})/$', 'path.to.month_view'),
(r'^people/(?P<state>\w\w)/(?P<name>\w+)/$', 'path.to.person_view'),
)
>>> from django.core import urlresolvers
>>> resolver = urlresolvers.RegexURLResolver(r'^/', settings.ROOT_URLCONF)
>>> resolver.reverse('path.to.foo_view')
'foo/'
>>> resolver.reverse('path.to.month_view', '2005', 'apr')
'dates/2005/apr/'
>>> resolver.reverse('path.to.person_view', state='il', name='adrian')
'people/il/adrian/'
>>> resolver.reverse('path.to.person_view', 'il', 'adrian')
# In the following, 'invalidstate' fails the regex test (it isn't two
characters long).
...
NoReverseMatch
{% link 'path.to.person_view' state='il' name='adrian' %}
fun. This means it'll probably break for wacky regexes, but I think a
95% solution is fine.
Adrian Holovaty
holovaty.com | djangoproject.com
|
|
urlresolvers.py 7K Download |
|
|
reverse_unit_tests.py 2K Download |