Redirect to last view after logging in

I struggled with this, sorted it out a bit and looked at the documentation, so I think its time to ask. I am trying to make my application redirected to the last page viewed after logging in. I am running django 1.2.4 and still no luck.

This stack overflow problem seemed as if it was a trick, but I had no success: Django: redirecting to the previous page after logging in ...

Currently, after logging in from any view, I am redirected to: // localhost: 1100 / accounts / profile /

settings.py has this code: "django.core.context_processors.request",

With this, as a login link: <a href="{% url django.contrib.auth.views.login %}?next={{request.path}}">login</a>

I also committed to import RequestContext into the views.py file: from django.template import RequestContext

I get the impression that this is not working. I also noticed now the login URL has a partial following URL: // localhost: 1100 / accounts / login /? next =

Suggestions? Thank you in advance!

+4
source share
2 answers

As sdolan said, you can use the login_required decorator, but there are also a few more options:

  • Form action:

     <form method="post" action="{% url django.contrib.auth.views.login %}?next={{request.path}}"> 
  • The following hidden field:

      <input type="hidden" name="next" value="{{request.path}}" /> 
  • With a link to the login form:

     <a href="{% url django.contrib.auth.views.login %}?next={{request.path}}">Login</a> 

To use them, you must pass the request context in the appropriate view. Examples of this can be found here: http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/

+5
source

If you use the login_required decorator in your views, it will automatically do it for you.

This is confirmed by experience and is explained in the documents:

If the user is not logged in, redirects to settings.LOGIN_URL, passing the current absolute path in the query string. Example: / Account / Login /? = Next / polls / 3 /.

+4
source

Source: https://habr.com/ru/post/1334299/


All Articles