How to redirect a Django template and use the 'Next' variable?
<p>I am using Django's built in login view as can be seen in the following snippets:</p>

<p><strong>urls.py</strong></p>

<pre><code>    url(r'^login$',login,{'template_name': 'login.html'},name="login"),
</code></pre>

<p><strong>template.html</strong></p>

<pre><code>&lt;form method="post" action="{% url 'login' %}"&gt;
{% csrf_token %}
&lt;table&gt;
&lt;tr&gt;
    &lt;td&gt;{{ form.username.label_tag }}&lt;/td&gt;
    &lt;td&gt;{{ form.username }}&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
    &lt;td&gt;{{ form.password.label_tag }}&lt;/td&gt;
    &lt;td&gt;{{ form.password }}&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;

&lt;input type="submit" value="login" /&gt;
&lt;input type="hidden" name="next" value="{{ next }}" /&gt;
&lt;/form&gt;
</code></pre>

<p>How can I use the next variable to redirect to a URL different than the default <em>/accounts/profile/</em> that django redirects to? I know of people referring to the settings.py file but I am wondering how I can utilize the next variable to do this?</p>

<p>(I'm not really sure of how the next variable works even after referring to documentation, an explanation of this would be much appreciated)</p>

<p>if you are using django login view ie,</p>

<pre><code>from django.contrib.auth.views import login
</code></pre>

<p>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</p>

<pre><code>settings.LOGIN_REDIRECT_URL is used
</code></pre>

<p>you can simple pass the next url just like, </p>

<pre><code>&lt;form method="post" action="{% url 'login' %}?next={{next_url}}"&gt;
</code></pre>

<p>Pass the "next_url" value via context. </p>

<p>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.</p>

<pre><code>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
</code></pre>

<p>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. </p>

<p>For login ref: <a href="http://stackoverflow.com/questions/806835/django-redirect-to-previous-page-after-login">Django: Redirect to previous page after login</a> </p>

python django django-forms django-templates django-views