Redirect to Next after login in Django

You can try:

return redirect(self.request.GET.get('next'))

The accepted answer does not check for the next parameter redirecting to an external site. For many applications that would be a security issue. Django has that functionality inbuilt in form of the django.utils.http.is_safe_url function. It can be used like this:

from django.shortcuts import redirect
from django.utils.http import url_has_allowed_host_and_scheme
from django.conf import settings

def redirect_after_login(request):
    nxt = request.GET.get("next", None)
    if nxt is None:
        return redirect(settings.LOGIN_REDIRECT_URL)
    elif not url_has_allowed_host_and_scheme(
            url=nxt,
            allowed_hosts={request.get_host()},
            require_https=request.is_secure()):
        return redirect(settings.LOGIN_REDIRECT_URL)
    else:
        return redirect(nxt)

def my_login_view(request):
    # TODO: Check if its ok to login.
    # Then either safely redirect og go to default startpage.
    return redirect_after_login(request)

You can try by simply add this input field before submit button in accounts/login.html template

<input type="hidden" name="next" value="{{ request.GET.next }}"/>

Tags:

Django

Login