让我修改这个问题
我有一个自己的登录视图,如下所示,正在实现@login_required
装饰器。
def do_login(request):
form = LoginForm()# create an instance of a login form
logged_in =request.user.is_authenticated() # get login status
if logged_in:
message='You are logged in '
return render_to_response('login.html',locals())# return
if request.method == 'POST':
usr=request.POST['username'] #get username
passwrd=request.POST['password']# get password
form=LoginForm(request.POST) # create instance of loginform
user=authenticate(username=usr,password=passwrd)# authenticate user
if user is not None:
if user.is_active:
login(request,user) #log user in
return HttpResponseRedirect("/login_success/")
else:
pass
else:
return render_to_response('login.html',locals())
else:
return render_to_response('login.html',locals())
这是有效的,因为任何时候我尝试访问网址(例如更改密码)都会被带到登录页面以便首先登录。在登录页面上,地址栏中显示的网址为http://myapp.com/login/?next=/change_password/
现在,当我登录时,我将转到http://myapp.com/login/login_success/
而不是http://myapp.com/login/change_password/
。在登录时,我希望自动重定向到我要求登录之前尝试前往的预期http://myapp.com/login/change_password/
。我该如何解决呢
答案 0 :(得分:0)
也许是这样的
模板:
{% if user.is_authenticated %}
<a href="{% url 'some_summary_url' %}">click me</a>
{% else %}
<a href="{% url 'login' %}?next={% url 'some_summary_url' %}">click me</a>
{% endif %}
查看:
return HttpResponseRedirect(request.GET.get('next', '/'))
答案 1 :(得分:0)
我发现了问题所在。我必须访问next
参数中的网址,例如{{request.GET.next}}
而不是{{next}}
所以我的代码改为:
在模板中,我在登录表单中添加了一个隐藏的输入,并将其值设置为{{request.GET.next}}
<input type="hidden" name="next" value="{{ request.GET.next }}" />
所以在我的登录视图中,我现在可以访问隐藏字段的值并使用该值在登录后进行重定向
def do_login(request):
form = LoginForm()# create an instance of a login form
logged_in =request.user.is_authenticated() # get login status
if logged_in:
message='You are logged in '
return render_to_response('reg/login.html',locals())# return
if request.method == 'POST':
usr=request.POST['username'] #get username
passwrd=request.POST['password']# get password
form=LoginForm(request.POST) # create instance of loginform
user=authenticate(username=usr,password=passwrd)# authenticate user
if user is not None:
if user.is_active:
login(request,user) #log user in
return HttpResponseRedirect(request.POST['next'])
else:
pass
else:
return render_to_response('reg/login.html',locals())
else:
return render_to_response('reg/login.html',locals())