cfpb / back-end

:warning: THIS REPO IS DEPRECATED :warning: – Please visit:
https://github.com/cfpb/development
Creative Commons Zero v1.0 Universal
3 stars 3 forks source link

Namespacing our Django app URLs #15

Open willbarton opened 8 years ago

willbarton commented 8 years ago

So, yesterday we noticed that clicking on the "About" link from anywhere in eRegulations would take you instead to this page:

http://www.consumerfinance.gov/retirement/before-you-claim/about/

Which is a placeholder page in the retirement app.

This happened because both regulations-site and retirement have a URL with the name "About", and our header in regulations-site simply calls it by that name ({% url 'about' %}).

In the overall CFPB Django project, the urls.py contains the eRegs urls:

    # eRegulations
    url(r'^eregs-api/', include('regcore.urls')),
    url(r'^eregulations/', include('regulations.urls')),

Before the retirement urls:

if 'retirement_api' in settings.INSTALLED_APPS:
    urlpatterns += patterns('',
         url(r'^retirement/', include('retirement_api.urls')),
)

And so the retirement URL named "about" is overriding the eRegs URL named "about".

Django has a handy way to prevent this from happening, URL Namespaces.

Instead of the above URL configuration, we'd use:

    url(r'^eregs-api/', include('regcore.urls', namespace='regcore')),
    url(r'^eregulations/', include('regulations.urls', namespace='regulations')),
    url(r'^retirement/', include('retirement_api.urls', namespace='retirement')),

And then in our templates and all our URL-name matching lookups:

{% url 'regulations:about' %} 

Admittedly, that's a tall-order for some projects (regulations-site among them). It's something I'm going to work toward, and I think it's something we all should work on whenever we touch a new package.

I do think all our new development should presume that an app will be namespaced.

Thoughts?

willbarton commented 8 years ago

There are potential problems with going through and explicitly namespacing all our URL resolutions in our apps (as @chosak points out; the namespace is decided at the project level with the code above, where the URL resolutions happen at the app level). The documentation suggests possible ways around this. I'll be experimenting further.

@chosak also suggests that we can probably automate the process for:

chosak commented 8 years ago

Here's a working test that checks all templates in a project and fails on non-namespaced URLs:

https://gist.github.com/chosak/8d7a30a4235efab0aad06589b66de1a6