djangodjango-debug-toolbar

Overriding/Adding to Django URLs in settings rather than urls


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)),
    ]

Solution

  • 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 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.