1

It seems that the latest Django debug toolbar module has changed to middleware now and requires explicit URL setup to work. With my Django projects I always try to keep settings organised based on environment and not have if settings.DEBUG littered all over the settings files and project.

My settings layout is a general:

common.py (everything in here)
development.py (dev only things here)
production.py (prod only things here)

Is there a way in Django 1.10 I can add to the URLs in the development.py file so that I can keep away from if settings.DEBUG. Or will we be forced to use this method if wanting to use the new version of the debug toolbar?

I just find the below a bit of an anti-pattern

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ]
pieterk
  • 305
  • 2
  • 17

1 Answers1

1

If you do not feel like testing for the value of settings.DEBUG in your URL configuration, you may manage your URLs with a pattern similar to the one you are using for your settings.

Instead of a urls.py file, you would have a urls package with this structure:

urls
├── __init__.py
├── common.py
├── local.py
└── production.py

In your different settings files you would specify which URL conf file to use this way:

# settings/local.py
ROOT_URLCONF = 'urls.local'

 

# settings/production.py
ROOT_URLCONF = 'urls.production'

The urls/common.py file will expose a urlpattern member containing all the URL patterns common to all configurations which you will import and use in urls/local.py and urls/production.py.

For example:

# urls/common.py
urlpatterns = [
    # Put all common URL patterns here
]

 

# urls/local.py
from .common.py import urlpatterns as common_urlpatterns

urlpatterns = common_urlpatterns + [
    url(r'^__debug__/', include(debug_toolbar.urls)),
]

If you want my opinion, this solution feels like overkill given that, as opposed to settings, URL configurations should not differ much between environments.

aumo
  • 5,344
  • 22
  • 25
  • Strangely enough, I did not think of this at first even though I am doing it for settings. DOH! But your method does seem like a reasonable option. Thank you – pieterk Jan 19 '17 at 13:55
  • This is a decent solution, thanks! One caveat about the module name. I'm using python 3.6 with Django 1.11 and it turns out it requires the absolute module path instead of relative `ROOT_URLCONF = '{{ project_name }}.urls'` so one would need to have `project_name` in the setting files, e.g. 'xxx.urls.local' – digit plumber Mar 10 '18 at 22:01