Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anyone knows good Django URL namespaces tutorial? [closed]

I'm looking for a good tutorial for URL namespaces in Django. I find official documentation a little too sparse - it lacks good examples. I found similar question here on stack, but the answers didn't help me to fully understand the subject either.

like image 699
minder Avatar asked Jan 24 '10 08:01

minder


People also ask

What does form {% URL %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .

What is URL namespace in Django?

URL namespaces allow you to uniquely reverse named URL patterns even if different applications use the same URL names. It's a good practice for third-party apps to always use namespaced URLs (as we did in the tutorial). Similarly, it also allows you to reverse URLs if multiple instances of an application are deployed.


1 Answers

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

In apps.help.urls:

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

In your main urls.py:

urlpatterns = [
    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.

like image 89
David Eyk Avatar answered Sep 19 '22 19:09

David Eyk