How can I disable Django's admin in a deployed project, but keep it for local development?

后端 未结 3 1018
悲&欢浪女
悲&欢浪女 2021-01-30 00:57

I am currently working in a Django project for which I need access to the admin area for local development, but want to disable it in the deployed site (for security reasons, am

相关标签:
3条回答
  • 2021-01-30 01:34

    First, establish a scheme so that your production server can have different settings than your development servers. A simple way to do that is with a source-control-ignored local_settings.py file, but there are many fancier ways to do it.

    Then, in your settings.py file, put:

    ADMIN_ENABLED = True
    

    and in your production-only settings file, put:

    ADMIN_ENABLED = False
    

    Then in your urls.py:

    if settings.ADMIN_ENABLED:
        urlpatterns += patterns('',
            (r'^admin/(.*)', include(admin.site.urls)),
            # ..maybe other stuff you want to be dev-only, etc...
            )
    
    0 讨论(0)
  • 2021-01-30 01:48

    Extending @NedBatchelder 's answer, you might want to use proper if statement, like this:

    if settings.ADMIN_ENABLED is True:
        ...
    

    And also remove 'django.contrib.admin' from INSTALLED_APPS = [...], and use the same condition:

    if settings.ADMIN_ENABLED is True:
        INSTALLED_APPS.append('django.contrib.admin')
    

    This way the module wont be loaded, and for eg. collectstatic wont copy unnecessary static files used only in admin (fonts, images, css, js).

    0 讨论(0)
  • 2021-01-30 01:50

    @madneon 's answer is terrific but requires an update and a small correction, and unfortunately the suggested edit queue is full.

    For the first part, as it implies the use of @Ned Batchelder 's answer, the use of patterns() is no longer supported in Django 1.9 and above.

    A current implemention could look like:

    from django.conf import settings
    from django.urls import path
    
    urlpatterns = []
    
    if settings.ADMIN_ENABLED is True:
        urlpatterns += [path('admin/', admin.site.urls),]
    
    urlpatterns += [
       # ... Other paths
    ]
    

    For the second part regarding appending to INSTALLED_APPS, this needs to go in the settings.py file and cannot be placed in the urls files.

    As such, it should be written:

    if ADMIN_ENABLED is True:
        INSTALLED_APPS.append('django.contrib.admin')
    

    If you include settings. before ADMIN_ENABLED you'll get an error.

    0 讨论(0)
提交回复
热议问题