Antoine Bouchard
Antoine Bouchard

Reputation: 55

Django URL: Multiple URL, same views. Then use {% url %} in template

I need 2 URLs to show the exact same view and URL patterns, so in my main urls.py file, I do this:

url(r'^evenements/', include('project.events.urls', namespace='events')),
url(r'^tourisme/evenements/', include('project.events.urls', namespace="tourisme_event", app_name='events')),

And then in my events app, I have this in the urls.py

urlpatterns = patterns('',
    url(r'^$', views.listing, name='index'),
    url(r'^(?P<slug>.*)/$', views.detail, name='detail'),
)

Now what I'm trying to achieve is to show the exact same view for both the URLs, but I need the links to work with this in the template:

{% url 'events:detail' event.event.slug %}

To my understanding, using "app_name" should allow me to do just that, but here are the different things that happen:

I can't get it to show a different URL on both pages. I did what was told in this answer: https://stackoverflow.com/a/8039846/2174532

Any idea why that wouldn't work? BTW, I'm on Django 1.6.

Thanks

Upvotes: 0

Views: 1095

Answers (1)

knbk
knbk

Reputation: 53699

Since you're not on 1.9 yet, you need to manually set a namespace hint to the current instance namespace. You can do so by passing the current_app to render() (or directly to your context instance):

render(request, 'template.html', current_app=request.resolver_match.namespace)

In 1.8 you set request.current_app instead of passing the namespace to the context. In 1.9, this is done for you.

You need to set the app_name to 'events' in both includes. Django will look for an application namespace, and only fall back to an instance namespace if no application namespace is found. If you name an instance namespace with no app_name the same as an application namespace, you'll never be able to reverse it.

Upvotes: 1

Related Questions