Search code examples
djangohttp-redirectauthenticationmixins

LoginRequiredMixin with redirect_field_name not redirecting


Using the LoginRequiredMixin it does not route to the 'redirect_field_name' I specify. Even though I see it appear in the url.

I've tried putting both urls ('user/update/') and named urls ('accounts:profile-update') in 'redirect_field_name' with the 'LoginRequiredMixin' but neither seem to make the redirect work.

I can get a redirect to work when I use the below, in src/settings.py LOGIN_REDIRECT_URL = '/user/'

But I want to have custom redirects for different views.

class ProfileUpdateView(LoginRequiredMixin, UpdateView):
    # http://127.0.0.1:8000/user/update/
    login_url = '/login/'
    redirect_field_name = 'accounts:profile-update'
    # redirect_field_name = '/user/update/'
    # neither works above
    model = Profile
    fields = ['first_name', 'last_name', 'mobile_phone',]
    template_name = 'accounts/profile_update.html'
    success_url = reverse_lazy('accounts:my-profile-detail')

    # PK required in UpdateView, making context['object']
    def get_object(self, queryset=None):
        if self.request.user.is_authenticated:
            queryset = Profile.objects.get(user=self.request.user)
        return queryset

# accounts/urls.py
app_name = 'accounts'
urlpatterns = [
    # ... some more urls ...
    path('update/', ProfileUpdateView.as_view(), name='profile-update'),
]

# src/urls.py
urlpatterns = [
    path('', include('django.contrib.auth.urls')),
    path('admin/', admin.site.urls),
    path('user/', include('accounts.urls')),
]

# src/settings.py
# LOGIN_REDIRECT_URL = '/user/'
# If I uncomment this, it works, but all my login's redirect only to this URL if I use LoginRequiredMixin :(```

Solution

  • You have misunderstood what redirect_field_name does.

    The redirect_field_name controls the name of the field, not the URL that you redirect to. For example setting redirect_field_name = 'nextpage' means that the LoginRequiredMixin will redirect to /login/?nextpage=/user/update/ instead of /login/?next=/user/update/.

    You don't usually want to override redirect_field_name. It's easier to stick with the default value next.

    The LoginRequiredMixin should automatically redirect to the previous page after logging in. If it doesn't after you have removed redirect_field_name and tried again, then the problem could be in your login view or template.