How to: Add a custom login screen for Django admin

Learn how to implement your own custom Django login screen
image
Scott James
Dec. 4, 2020
680 Views
2 min.
Tags:

Overview


In this quick tutorial we will learn a quick and easy way to spice up a Django app with a custom login screen for Django admin. While there are many ways to customise Django admin templates (which I will cover in another blog), this is an easy way to ensure continuity of all pages on your site that are accessible by an anonymous end user.

 

Ingredients


  • Any Django project

 

The Recipe


Let's have a look at the problem to start, The standard Django login screen is functional, yes, but in almost 100% of cases the design will be in stark contrast to the rest of your site, and your end users can potentially see that. Yuck! To solve this, lets go over an easy way to update the login template without getting into the nitty gritty of the admin or its existing functionality.

  1. Locate the existing Django login template at:

    "yourEnv/lib/pythonX.X/site-packages/django/contrib/admin/templates/admin/login.html"

  2. Copy the existing Django login template to your desired template directory
    In my case I use my own Django app called "core" to handle generic (eg. home page, 404/500 page) views, templates and urls for my website. So I will place my custom login template in the location:

    "myProject/core/templates/core/login.html"

    NOTE: 'DIRS': ['core/templates'], & 'APP_DIRS': True, must be present in the templates section of your settings.py to ensure Django looks for templates within your app directories
  3. In your apps views.py add the following code:
    |||{"file":"views.py"}|||
    from django.contrib.auth.views import LoginView
    
    class Login(LoginView):
    template_name = 'yourApp/login.html'
  4. In your projects root urls.py add the following code. Making sure the login path is placed before the default path for Django admin:
    |||{"file":"urls.py"}|||
    from yourApp.views import Login
    
    urlpatterns = [
        path('admin/login/', Login.as_view(), name='login'),
    ]
  5. At this point the deafult login template has been overridden with your own login.html file. You are now free to customise this template as your wish to bring it into line with the rest of your site!

 

The Result


The image below shows the updated login screen for this site. If you would like to see exactly how I put together my login template, the code is available here

Custom Django admin login view