How to automatically add a url param to url tags (it is used ubiquitously throughout application)?

24 views
Skip to first unread message

br

unread,
Jul 8, 2011, 6:38:34 PM7/8/11
to Django users
Here's a snippet from my base urls.py:

(r'^(?P<org_slug>[\w-]+)/manager/mobile/',
include('mobilepolls.manager.urls')),
(r'^(?P<org_slug>[\w-]+)/manager/display/',
include('screens.manager.urls')),
(r'^(?P<org_slug>[\w-]+)/display/', include ('screens.urls')),

Each of those apps then defines its own urls.py with various different
url patterns.

My problem is that I'm having to repeat the following:
{% url . . . org_slug=organization.slug %}

nearly everywhere I ever use a url tag in a template (probably 50x or
more), because the org_slug is ubiquitous in almost all urls, but is
always just retreived from the current user's organization. Doesn't
seem very DRY and is a bit error-prone. Is there anyway to automate
this with a custom tag or middleware or something so that i can just
assume that "org_slug=organization.slug" part of each url tag or add
it if there is a org_slug regex param in the url?


Background: We recently added organizations in our application to
provide a single-DB multi-tenancy of sorts. A user's organization is
reflected in most of the URL's he/she navigates to. As a shortcut to
not always have to access the organization via the
user.get_profile().organization, I add the current organization (which
is just a lazy functional reference to a user profile object's
organization property) to the request via middleware and to each
request context via a context processor .

Thanks,

Ben

br

unread,
Jul 9, 2011, 3:13:53 AM7/9/11
to Django users
FYI i ended up basically created a custom {% url %} tag, which is a
wrapper for the django standard url tag, but which adds the org_slug
as a parameter. Its a bit hacky/magical but saved me a bunch of
time. If any one runs into this issue, email me and I can show you
what I did.

VWAllen

unread,
Jul 9, 2011, 5:42:23 PM7/9/11
to django...@googlegroups.com
django-localeurl uses a similar URL scheme to localized urls (i.e. "/en/some/path" becomes "some/path" with an extra environment variable for localization).
You could check the source to see how it's being done there and adapt it: https://bitbucket.org/carljm/django-locale
It uses custom middleware to update the request path after stripping the appropriate part.

V
Reply all
Reply to author
Forward
0 new messages