无法解析?next =来自http:// login /?next = / my_page /使用request.GET.get('next','')的值

时间:2014-01-10 19:24:52

标签: django django-views

我有自定义登录网址/视图/模板。我将@login_required装饰器用于页面(让我们 称之为my_page,需要登录。试图访问

my_site.com/my_page 

正确调用

my_site.com/login/?next=/my_page/ 

但我的观点无法解析?next = / my_page / my 的值,而是始终重定向到我的默认视图,即 / qa /

def login_with_email(request):
    error = ''
    if request.method == 'POST':
        if not request.POST.get('email', ''):
            error = 'Please enter your email and password'
        if not request.POST.get('password', ''):
            error = 'Please enter your email and password'    
        if not error:    
            email = request.POST['email']
            password = request.POST['password']

            try:
                user = User.objects.get(email=email)
                user = authenticate(username=user.username, password=password)
                if user is not None:
                    if user.is_active:
                        login(request, user)

                        # *** 
                        next_page = request.GET.get('next', '/qa/')
                        response = HttpResponseRedirect(next_page)
                        # ***

                        response.set_cookie('login_email', email, max_age=14*24*60*60)
                        return response
            except User.DoesNotExist:    
                error = 'Invalid email and password combination'

Urls.py:

url(r'^login/$', views.login_with_email), 

1 个答案:

答案 0 :(得分:1)

根据我在下面的评论,我意识到我必须在我的POST处理之前从中获取next的值<感谢@Anentropic在灯泡上闪烁)。所以现在我抓住next的值,将其传递给我的模板,然后将其存储在隐藏字段中,最后使用request.POST.get在重定向需要时访问它。

修订后的观点:

def login_with_email(request):
    error = ''
    next = request.GET.get('next', '/qa/profile/private/')
    if request.method == 'POST':
    ...
                if user.is_active:
                    login(request, user)
                    next = request.POST.get('next', '/qa/profile/private/')
                    ...    
    return render(request, 'qa/login_with_email.html', {'error': error, 'login_email': login_email, 'next': next,})

在我的模板中:

<form method="post" action="." autocomplete="on">{% csrf_token %} 
    <p><input type="hidden" name="next" value="{{ next }}"/></p>
    ...

注意:此答案最初是由问题的发布者发布的。我把它搬到了这里。