A slight modification (and, I think, improvement) of the URL decorator found in snippet 395.
What's different between this snippet and 395?
- We use
django.conf.urls.defaults.url()
when adding patterns - We support arbitrary arguments to the
url()
method (likename="foo"
) - We do not support multiple url patterns (this didn't seem useful to me, but if it is I can add it back.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | import sys
from django.core.urlresolvers import RegexURLResolver
from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url as dcud_url
#
# Annotate a view with the URL that points to it
#
def url(pattern, *args, **kwargs):
"""
Usage:
@url(r'^users$')
def get_user_list(request):
...
@url(r'^info/(.*)/$', name="url-name")
@render_to('wiki.html')
def wiki(request, title=''):
...
"""
caller_filename = sys._getframe(1).f_code.co_filename
module = None
for m in sys.modules.values():
if m and '__file__' in m.__dict__ and m.__file__.startswith(caller_filename):
module = m
break
def _wrapper(f):
if module:
if 'urlpatterns' not in module.__dict__:
module.urlpatterns = []
module.urlpatterns += patterns('', dcud_url(pattern, f, *args, **kwargs))
return f
return _wrapper
#
# Continue the @url decorator pattern into sub-modules, if desired
#
def include_urlpatterns(regex, module):
"""
Usage:
# in top-level module code:
urlpatterns = include_urlpatterns(r'^profile/', 'apps.myapp.views.profile')
"""
return [RegexURLResolver(regex, module)]
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.