开发者

Redirecting to last view after login

I have wrestled with this one for a bit and googled and looked through documentation, so I guess its time to ask. I am trying make my app redirect to the last viewed page after logging in. I am running django 1.2.4 and have had no luck so far.

This Stack Overflow thread seemed like it would do the trick but I have not had success with it: Django: Redirect to previous page after login...

Currently after logging in from any view I am redirected to: //localhost:1100/accounts/开发者_开发技巧profile/

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

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

I also made sure to import the RequestContext in my views.py file: from django.template import RequestContext

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

Suggestions? Thanks in advance!


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

  • Form action:

    <form method="post" action="{% url django.contrib.auth.views.login %}?next={{request.path}}">
    
  • Next 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>
    

For using them, you have to pass the Request Context in the corresponding view. Examples of doing this can be found here: http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/


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

This is confirmed by experience, and explained in the docs:

If the user isn't logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string. Example: /accounts/login/?next=/polls/3/.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜