0

让我修改这个问题

我有一个自己的登录视图,如下所示,并且正在实现@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())

这很有效,因为每当我尝试访问一个 url(例如更改密码)时,都会被带到登录页面以首先登录。在登录页面时,地址栏中显示的 url 是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/被要求登录之前尝试访问的目标。请问我该如何解决

4

2 回答 2

0

我发现了问题所在。我必须访问next参数中的 url,{{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())
于 2012-08-31T19:49:22.437 回答
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', '/'))
于 2012-08-30T11:10:36.420 回答