views:

55

answers:

1

Assume a Django app, shop, whose urls.py is included in the main urls.py:

# main urls.py
urlpatterns = patterns('',
    (r'^[^/]+/shop/', include('shop.urls')),
)

Note, that there is an arbitrary prefix before /shop. This is of no interest for the shop app, it's only interesting to some middleware.

The shop.urls could look like this:

# shop's urls.py
urlpatterns = patterns('',
    url(r'^$', index, name="shop_index"),
    url(r'^product/(?P<id>[^/]+)$', product, name="shop_product"),
)  

I now want to use {% url %} in my shop templates. What overthrows this plan is, that the generated URL doesn't include the prefix from the global urls.py. The generated URLs look more like, e.g.

/^/shop/product/1

Question: Now, is there a possibility (in Django 1.2 or svn trunk) to enable the reverse lookup to use just the same prefix, that is there in the current URL? For example, if request.path is /foo/shop/, that {% urls shop_product id=1 %} returns

/foo/shop/product/1

The only way I came up with is to embrace the prefix and send it to the shop app views, but this is a really bad solution, since shop then has to deal with something it doesn't need at all.

+1  A: 

No there is not, not a straightforward django way anyway. Django has no idea of knowing what you mean with [^/]+, in your case that it is a prefix that should be dynamically be added to a reverse url lookup.

I wonder also why you add middleware specific info to an url and not even as GET paramters, doing something like this is jsut asking for trouble imho. If you say the prefix is middleware-specific, it doesn't make sense to mess with it somewhere outside of the middleware.

A solution that could work (did not test it) is setting in your middleware a request context variable like environment_prefix, then append this manually before the url. So something like this:

/{{ environment_prefix }}{% filter slice:"1:" %}{% url shopview %}{% endfilter %}

Another possiblity is to try to implemented your own url template tag (inheritted from the url templatetag) to always include the current prefix which can again be a context variable set by the middleware.

KillianDS
Hm, I feared so (and started mentally to implement a url templatetag extension). Thanks for the answer.
Boldewyn