title: In Django, after login redirect the user to the previous page
body: <p>I want to secure each webpage of my django app, and what I want is that after login the user should be redirected to the previous page he was trying to access. So <strong>in accounts/views.py</strong> this is the login function I am using for that:</p>
  <pre><code>def login(request):
      if request.method == 'POST':
          #some code
  
          if user is not None:
              auth.login(request, user)
              return redirect(request.POST.get('next','dashboard'))
          else:
              #some code
  
      else:
          #some code
  </code></pre>
  <p>Now, I have used <code>@login_required</code> condition for each view of my webapp in this way:</p>
  <pre><code>@login_required(login_url='login')
  def profile(request):
      return render(request, 'profile.html')
  </code></pre>
  <p><strong>my login.html (<a href="https://stackoverflow.com/questions/21693342/django-after-login-required-redirect-to-next">reference</a>):</strong></p>
  <pre><code>&lt;form method=&quot;POST&quot; action=&quot;/accounts/auth&quot;&gt;
      {% csrf_token %}
      &lt;input type=&quot;hidden&quot; name=&quot;next&quot; value=&quot;{{ request.GET.next }}&quot; /&gt;
      {{ login_form }}
      &lt;input type=&quot;submit&quot;&gt;
  &lt;/form&gt;
  </code></pre>
  <p>Now if the user visits <code>accounts/profile</code> without login, then he is redirected to <code>accounts/login?next=/accounts/profile</code>, so after login he is successfully redirected to <code>accounts/profile</code> as the value of <code>'next'</code> is set to <code>/accounts/profile</code> and in login function if the user is authenticated then i have used <code>return redirect(request.POST.get('next','dashboard'))</code> which means redirect to the value of <code>next</code> if it is entered, otherwise <code>/accounts/dashboard</code>.</p>
  <p><strong>Now coming to my issue,</strong> if I try to access the login page directly (i.e. <code>/accounts/login</code>) then as there is no <code>next</code> variable in the URL, so according to my <code>login</code> function I should be redirected to <code>/accounts/dashboard</code> <strong>but instead, I am getting the following error:</strong> <code>Reverse for '' not found. '' is not a valid view function or pattern name.</code> what am I doing wrong?</p>
  <p><strong>Extra note</strong>: I have even tried adding <code>LOGIN_REDIRECT_URL='dashboard'</code>  to my <code>settings.py</code> but still when the <code>next</code> variable is blank I am not redirected to the <code>dashboard</code></p>
  <p><strong>Mostly the mistake is in this piece of code:
  <code>redirect(request.POST.get('next','dashboard'))</code></strong></p>