Search code examples
djangoauthenticationdjango-views

Login redirects in Django


I have a auth system with django-allauth library, and i have some login, logout functionally implemented and it works fine. But I want to implement a profile page on my own. With this I'm so confusing right with Django redirects.

I have a class based view called HomeRequestHandler that inherits a LoginRequiredMixin:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView


class HomeRequestHandler(LoginRequiredMixin, TemplateView):
    template_name = "home.html"

And in my urls i just call it to "":

from django.views.generic import TemplateView
from django.urls import path
from . import views

urlpatterns = [
    path("", views.HomeRequestHandler.as_view(), name="home"),
    path("profile/", TemplateView.as_view(template_name="account/profile.html"), name="profile"),
]

In my settings.py, I have a constant for LOGIN_REDIRECT_URL:

LOGIN_REDIRECT_URL = reverse_lazy('profile')

When I try login, I am redirected to "/" even with LOGIN_REDIRECT_URL defined. But if I change one thing in my view:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView


class HomeRequestHandler(LoginRequiredMixin, TemplateView):
    template_name = "home.html"
    redirect_field_name = "redirect_to"

It change my url http://localhost:8000/accounts/login/?next=/ to http://localhost:8000/accounts/login/?redirect_to=/ and now the constant works normally, why???


Solution

  • In Django by default, LoginRequiredMixin uses the ?next= parameter to redirect after login. This parameter is appended to the URL automatically when Django redirects unauthenticated users to the login page. Ref.

    You have set LOGIN_REDIRECT_URL = reverse_lazy('profile') in your settings.py file which is supposed to redirect users to the profile page after login but this setting is only used when there is no ?next= parameter present in the URL, or when the user logs in directly from the login page without being redirected from another protected page.

    When you modified the HomeRequestHandler class to include redirect_field_name = "redirect_to", you essentially changed the query parameter that LoginRequiredMixin looks for. Instead of using next, it now looks for redirect_to. So, when Django doesn't find a redirect_to parameter (because it's not the default behavior), it falls back to using the LOGIN_REDIRECT_URL setting.