python - 登录后重定向回上一页(Django)

标签 python django

我在几个页面中创建了登录页面强制登录。现在我需要在成功登录后重定向回上一页。

当我通过@login_required(login_url='/login/')强制登录时。它在查询字符串中包含 next 参数。

enter image description here

我尝试使用 redirect_to = request.REQUEST.get('next', '') 捕获它并将其发送到重定向 return HttpResponseRedirect(redirect_to) 但没有不起作用。

view.py

def login(request):
    def errorHandle(error):
        form = LoginForm()
        return render_to_response('login/login.html', {
            'error' : error,
            'form' : form,
            })
    if request.method == 'POST': # If the form has been submitted...
        form = LoginForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            username = request.POST['username']
            password = request.POST['password']
            redirect_to = request.REQUEST.get('next', '')
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    # Redirect to a success page.
                    auth_login(request, user)
                    return HttpResponseRedirect(redirect_to)
#                    return render_to_response('login/logged_in.html', {
#                        'username': username,
#                        })
                else:
                    # Return a 'disabled account' error message
                    error = u'Account Disabled'
                    return errorHandle(error)
            else:
            # Return an 'invalid login' error message.
                error = u'Invalid Login'
                return errorHandle(error)
        else:
            error = u'Form is Invalid'
            return errorHandle(error)
    else:
        form = LoginForm() # An unbound form
        return render_to_response('login/login.html', {
            'form': form,
            })

模板

<div id="login_form">
<form action="." method="post">
    {{ form.as_p }}
    <input type="submit" value="Login">
</form>
</div>

编辑 - 我发现了这个问题。我的模板有问题。下面这个表格效果很好。

    <form action="" method="post">
        <label for="username">User name:</label>
        <input type="text" name="username" value="" id="username">
        <label for="password">Password:</label>
        <input type="password" name="password" value="" id="password">

        <input type="submit" value="Login" id="button"/>
        <input type="hidden" name="next" value="{{ next|escape }}" />
    </form>

最佳答案

您可以将其添加到表单中:

<input type="hidden" value="{% if request.REQUEST.next %}{{ request.REQUEST.next }}{% else %}{% if request.META.HTTP_REFERER %}{{ request.META.HTTP_REFERER }}{% else %}/{% endif %}{% endif %}" name="next" />

以下是它解决的情况:

  1. 如果用户来自login_required View :next由login_required设置
  2. 如果用户来自登录表单(即身份验证未通过):next=之前设置的下一个值
  3. 如果用户来自非 login_required View :next=引荐网址
  4. 如果用户直接打开登录页面:next=/

请注意,这也适用于外部登录 View ,您应该使用它。

作为一个好东西,这是我的注销模板的一部分,它将用户重定向到他注销之前所在的页面。

{% block body %}
    <p>{% trans "You've been logged out." %}</p>
    {% if '/account/logout/' not in request.META.HTTP_REFERER %}
    <p>
        {% trans 'You will be redirected in a second' %}
    </p>
    {% endif %}
{% endblock %}

{% block extra_body %}
    {% if '/account/logout/' not in request.META.HTTP_REFERER %}
        <script type="text/javascript">
        document.location.href = '{{ request.META.HTTP_REFERER }}';
        </script>
    {% endif %}
{% endblock %}

我要感谢雇用我的伟大初创公司 sports pick, tipster social network因为它们允许我 0)共享代码和 1)利用我的一些时间来帮助其他人。但我链接它的真正原因是为了让您可以测试它。如果此代码对您不起作用,就像它在那里一样,那么您就会遇到另一个问题。

关于python - 登录后重定向回上一页(Django),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9989149/

相关文章:

python - 在 Google App Engine (python) 中从 Google Cloud Storage 读取文件时出现内存泄漏

Python/MySQL Select 返回 None with %s

python - 使用 BeautifulSoup python 3.6 抓取数据时缺少网页值

python - 在 Django 项目中使用 Twisted 进行异步调用

javascript - 如何将 python/Django 列表/字典转换为 javascript

python - 如何在一个页面中显示多条django消息?

python - django.core.exceptions.FieldDoesNotExist : User has no field named 'username'

python - 如何打开执行 python 文件的终端

python - pymongo-upsert 无法使用 $set 操作执行插入

python - Django:带有选择列表的自引用外键