Protected Admin Page with Password Reset Feature

In this quick tutorial, we are going to learn how to protect your application against malicious automated scripts that look for admin panels. Since in Django and WordPress applications, these are located at the standard /admin path of a website, it is advisable to change your admin location. This is actually really easy to do. This is just another security measure that should be taken prior to deployment.

Firstly, in your .env file which should be located within your project's source directory (the same level as your manage.py file), set up an environment variable called ADMIN_ALIAS or something similar.

ADMIN_ALIAS=custom-slug-to-admin-panel

You can, of course, change the example string custom-slug-to-admin-panel to be whatever your preferred location of the admin panel will be.

Next up, when your project runs, it needs to get the environment variable into the settings. For a simple, key/value pair storage within your .env file, this is achieved like this.

# In your project's settings.py

# Additional field to adjust the login point for the Admin site
ADMIN_ALIAS = os.environ['ADMIN_ALIAS']

Finally, all of the URLs within your project that pertain to the admin panel need some adjustments so that when the administrator of the website navigates to them, they will still access them as they would do if the admin was delivered out of the box by Django.

from django.contrib.auth import views as auth_views
from django.urls import path
from my_project.settings import ADMIN_ALIAS


urlpatterns = [
    path(
        f'{ADMIN_ALIAS}/password_reset/',
        auth_views.PasswordResetView.as_view(),
        name='admin_password_reset',
    ),
    path(
        f'{ADMIN_ALIAS}/password_reset/done/',
        auth_views.PasswordResetDoneView.as_view(),
        name='password_reset_done',
    ),
    path(
        'reset/<uidb64>/<token>/',
        auth_views.PasswordResetConfirmView.as_view(),
        name='password_reset_confirm',
    ),
    path(
        'reset/done/',
        auth_views.PasswordResetCompleteView.as_view(),
        name='password_reset_complete',
    ),
    path(f'{ADMIN_ALIAS}/', admin.site.urls),
    ...
]

Now, your site has an additional level of protection applied.