Asur
Asur

Reputation: 2057

Django - Why url namespaces?

I've been learning Django for sometime now. I came across url reverse, understood most of it but couldn't understand namespaces:

1. How is it useful ?
2. How to use it ?

It is poorly documented and I've not found any decent article on it. :(


Also could someone explain how to reverse included urls??

Upvotes: 0

Views: 84

Answers (1)

madhu131313
madhu131313

Reputation: 7386

i found a good solution here Anyone knows good Django URL namespaces tutorial?

Disclaimer : This is written by David Eyk on above mentioned link

Agreed, the docs for this are rather confusing. Here's my reading of it (NB: all code is untested!):

In apps.help.urls:

urlpatterns = patterns(
    '',
    url(r'^$', 'apps.help.views.index', name='index'),
    )

In your main urls.py:

urlpatterns = patterns(
    '',
    url(r'^help/', include('apps.help.urls', namespace='help', app_name='help')),
    url(r'^ineedhelp/', include('apps.help.urls', namespace='otherhelp', app_name='help')),
    )

In your template:

{% url help:index %}

should produce the url /help/.

{% url otherhelp:index %}

should produce the url /ineedhelp/.

{% with current_app as 'otherhelp' %}
    {% url help:index %}
{% endwith %}

should likewise produce the url /ineedhelp/.

Similarly, reverse('help:index') should produce /help/.

reverse('otherhelp:index') should produce /ineedhelp/.

reverse('help:index', current_app='otherhelp') should likewise produce /ineedhelp/.

Like I said, this is based on my reading of the docs and my existing familiarity with how things tend to work in Django-land. I haven't taken the time to test this.

Upvotes: 1

Related Questions