python - 有没有办法将我的 django 登录表单嵌入到我的 base.html 模板中?
问题描述
我目前正在制作一个 django 学校系统,并且遇到了一个难题。虽然我已经成功地制作了一个正常运行的登录系统,但我看到的所有教程都包含一个单独的登录表单页面。考虑到我的网站是 LOGIN ONLY ACCESS,我在 base.html 模板上有一个 if 语句,它将根据用户是否登录来显示内容。如果用户登录,它会显示正确的内容,但是,我不知道如何将我的登录表单嵌入到 base.html 中,因此我可以将其插入到 if/else 语句中。有什么简单的方法可以做到这一点?如果需要,我会分享我的代码。
当前的 base.html 文件
<body>
{% if user.is_authenticated %}
THIS CONTENT IS CORRECTLY SHOWING
{% else %}
THIS IS MEANT TO BE LOGIN FORM
<div class="container">
<form method="post" action='users/login'></form>
{% csrf_token %}
<div class="row justify-content-center">
<div id="login-box" >
<div class="login-text mb-2" >Login for Access</div>
{{ form|crispy }}
<button type="submit" class="btn btn-primary mt-2 mb-2">Login</button>
<br> <a href="#" data-toggle="tooltip" data-placement="bottom" title="
Please contact your IT Administrator at college for information on how
to reset your password">Forgot Password?</a>
</form>
</div>
</div>
</div>
{% endif %}
</body>
</html>
我的代码当前显示的内容如下。
解决方案
在模板中,您可以按如下方式区分视图以分隔视图
{% if not request.user.is_authenticated %}
SHOW THE CONTENT FOR NOT LOGGED IN USERS
{% else %}
SHOW THE CONTENT FOR LOGGED IN USERS
{% endif %}
并且您的登录可以在 html 表单元素上的 base.html 文件上完成,动作属性指向登录 url
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>