0

I tried to make some pages only visible when logged in.

I tried it with:

 def backend(request):
    if request.user.is_authenticated:
        return render(request, 'web/backend-index.html')
    else:
        return redirect(reverse('web:login'))

and also with:

@login_required
   def backend(request):
   return render(request, 'web/backend-index.html')

The first code does not let me log in.

The second code does not let me log in but the url changes too: http://127.0.0.1:8000/login/?next=/backend/

If I just render the view without checking if logged in, the login is working fine and I´ll be passed to the backend page.

The whole code is on github: https://github.com/psmaster1/BrainSystems/tree/master/smarthome/web

I don't get any error messages. It's just redirecting to the login page...

4

2 回答 2

1

您的登录表单不正确 - 这就是您从未真正进行身份验证的原因。它正在向不正确的端点发送 POST 请求,并且没有呈现实际形式。这是您可以手动呈现字段的方式

将其更改为:

<section class="login-form">
    <div class="login-fields">
        <h3>Login</h3>
        <form method="POST">
            {% csrf_token %}

            <div class="form-group">
                {{ login_form.username }}
                <label for="{{ login_form.username.id_for_label }}" class="control-label">Username</label><i class="bar"></i>
                {{ login_form.username.errors }}
            </div>

            <div class="form-group">
                {{ login_form.password }}
                <label for="{{ login_form.password.id_for_label }}" class="control-label">Passwort</label><i class="bar"></i>
                {{ login_form.password.errors }}
            </div>

            <div class="button-container">
                <input type="submit" class="button" value="Login" />
            </div>
        </form>
        <p>Noch nicht Registriert?</p>
        <a href="{% url 'web:register' %}">Registrieren</a>
    </div>
</section>
于 2019-05-17T19:43:47.673 回答
0

已经修好了!问题是表单标签中的动作属性。它会引起麻烦。刚刚从表单标签中删除它并在 login() 方法中进行重定向。多谢你们!:)

于 2019-05-17T19:57:43.413 回答