使用django 2.2登录时将登录页面重定向到主页

时间:2019-07-06 17:30:25

标签: html django

我要在用户已经登录并尝试再次访问登录页面时将其重定向到主页。我正在使用django 2.2。我尝试使用user.is_authenticated,但是没有用

{% block content %}
{% if user.is_authenticated %}
    {% block chess_page %}
    {% endblock %}

{% else %}
    <div id="logo">
        <img src="../../static/img/chess-logo.jpg" name="logo-pic">
        <h2>Chess</h2>
    </div>
    <form method="post">
      {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Login</button>
    </form>
{% endif %}
{% endblock %}

chess_page是我要重定向到的主页

1 个答案:

答案 0 :(得分:0)

与其在模板中检查user.is_authenticated而不是在用于呈现登录页面的视图中检查它,而是在登录视图中检查request.user.is_authenticated,然后根据is_authenticated条件重定向到主页,如下所示:

def login(request):
    if request.user.is_authenticated:
        # redirect to homepage
        # "chess_page" is the name you gave while creating url
        return HttpResponseRedirect(reverse("chess_page"))
    else:
        # render login page
        return render(request, "login.html")
相关问题