[Django]-How to redirect a Django template and use the 'Next' variable?

6👍

if you are using django login view ie,

from django.contrib.auth.views import login

you just need to pass the next url to the template. so when the request is sent to the login view , the code is in place to redirect to that url. is no next url is found

settings.LOGIN_REDIRECT_URL is used

you can simple pass the next url just like,

<form method="post" action="{% url 'login' %}?next={{next_url}}">

Pass the “next_url” value via context.

The next case, if you need the next url redirection for any of you custom views, simple write a code inside the view to get next url and after doing the job inside the view you can redirect to the next url.

from django.utils.http import is_safe_url

def your_view(request):
    # do your codes
    redirect_to = request.GET.get(next, '') # use get or Post as per your requirement 
    if is_safe_url(url=redirect_to, host=request.get_host()):
        HttpResponseRedirect(redirect_to)
    else:
        # your response

To clear your doubt how the next variable works: In the above view we get a get a http request and if we have passed the next url as query params. we will be getting it in the view. “request.GET.get(next, ”)” will get you the next url you sent from view. from view level you can do the functionalities you need and then if the next url is present and valid you can use HttpResponseRedirect to redirect to the next url.

For login ref: Django: Redirect to previous page after login

Leave a comment