Django admin - custom login

Hello,

I have a Django application with a large number of users, organized into groups. I use LDAP authentication, but I also need regular username/password login for some staff members and superusers, so I am using multiple authentication backends.

I implemented a custom login service that tracks failed login attempts and locks users after a certain number of retries. This approach works well for regular users, because I call the login_service in views.py, where the login forms are handled.

The problem appeared when I needed to log in through the Django admin interface. I want to keep all the default ModelAdmin functionality, but I also need to apply my custom login service there. I’m not sure what the best way to implement this would be.

I tried implementing another authentication backend to handle admin authentication, but the issue is that users who are not authenticated via LDAP or ModelBackend end up being authenticated by this custom admin backend.

Could you please give me some advice or best practices for handling this scenario?

I’m not sure I follow what exactly you need to apply or what you mean by a “custom login service”. If this is a custom login view that you have created, you can configure Django to use it instead of the standard LoginView.

You can override the Django admin login view by registering your own view at the admin/login/ url.

For example, say you have something like:

urlpatterns = [
    ...
    path('admin/', admin.site.urls),
    ...
]

If you add your login page before this, Django will find your view before dispatching to the admin-provided login view.

urlpatterns = [
    ...
    path('admin/login/', my_login_view),
    path('admin/', admin.site.urls),
    ...
]

This view can then implement your login service.