Exclude specific auth.urls routes
2 min read

Exclude specific auth.urls routes

This overrides the urlpatterns for the standard django.contrib.auth.urls and makes it easy to exclude whichever paths you no longer need from your routing. It's a small thing, but it keeps your end-product nice and tidy for the users.
Exclude specific auth.urls routes

I was recently setting up authentication for a new site written using Django, and as part of this I overrode a couple of the included authentication views so I could add messages and change the redirect on success.

For example, the PasswordResetConfirmView now redirects to login on success.

class ConfigPasswordResetConfirmView(SuccessMessageMixin, PasswordResetConfirmView):
    success_url = reverse_lazy("login")
    success_message = "Your new password has been set. You may log in now."

Sidenote: I always name my Django project config, and collect any centralised functionality here.

I did the same thing with PasswordChangeView, which rendered the password_change_done authorisation view redundant. So instead of redirecting to a view that simply displayed a success message, I redirected to somewhere more sensible and used the built in message functionality to display the success message for a more standard look.

This all works nicely, but of course it now means that the authentication view password_reset_complete is now redundant. Again, it's not really a problem, but remember we usually import all auth views in our project, like this:

urlpatterns = [
    ...
    path("auth/", include("django.contrib.auth.urls")),
    ...
]

This means that the redundant views are still there, and can be accessed directly via their urls, so pages like this are still available:

django_password_reset_done
Not the end of the world perhaps, but not great either, since I assume your site looks completely different from the standard admin view, and having this pop up for a user might be very confusing.

So, I decided to get rid of them, which turned out to be quite simple in the end.

I created a new file: config/urls_auth.py, which I then used for the include in the regular urls.py file, like this:

urlpatterns = [
    ...
    path("auth/", include("config.urls_auth")),
    ...
]

And set up urls_auth.py like this:

from django.contrib.auth.urls import urlpatterns as original_urlpatterns


exclude_patterns = ["password_change_done", "password_reset_complete"]

urlpatterns = [pattern for pattern in original_urlpatterns if pattern.name not in exclude_patterns]

This overrides the urlpatterns for the standard django.contrib.auth.urls and makes it easy to exclude whichever paths you no longer need from your routing.

It's a small thing, but it keeps your end-product nice and tidy for the users.

Enjoying these posts? Subscribe for more