![](/img/trans.png)
[英]How do I make the edit and cancel link appear only if its the logged in user is the one who created the object? Django
[英]Django: login link to appear only when a user is logged in
我正在 django 中制作一个应用程序,其中我使用了 django 内置的身份验证系统。 导航栏中存在登录和注销链接。 我想让注销链接仅在用户登录时出现,而不是一直出现。 我怎么做?
project/urls.py
代码片段:
urlpatterns = [
url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'),
url(r'^logout/$', views.logout, {'next_page': '/home'}), ]
login.html
代码片段;
<div class="container">
<section id="content">
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
{% if next %}
{% if user.is_authenticated %}
<p>Your account doesn't have access to this page. To proceed,
please login with an account that has access.</p>
{% else %}
<p>Please login to see this page.</p>
{% endif %}
{% endif %}
<form action="{% url 'login' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h1>Login Form</h1>
<div class="imgcontainer">
<img src="{% static 'student/patient.jpg' %}" alt="Avatar" class="avatar">
</div>
<div class="username">
{{ form.username.label_tag }}
{{ form.username }}
</div>
<div class="password">
{{ form.password.label_tag }}
{{ form.password }}
</div>
<div class="submitb">
<input type="submit" value="Log In" name="mybtn">
</div>
<div class="resetb">
<input type="submit" value="Reset">
<a href="#forgotpwd">Forgot password?</a>
</div>
<input type="hidden" name="next" value="{{ next }}" />
</form>
base.html
代码片段(仅显示导航栏):
<ul>
<li><a class="active" href="/home">Home</a></li>
<li><a href="/about">About </a></li>
<li><a href="/signup">Sign up</a></li>
<li><a href="#">Doctor's login</a></li>
<li><a href="{% url 'login' %}?next={{request.path}}">Patient's login</a></li>
<li><a href="#about">FAQs</a></li>
<li><a href="/contact">Contact us</a></li>
<li><a href="#about">Reviews</a></li>
<li><a href="/logout">Logout</a></li>
</ul>
提前感谢您的帮助。
将注销列表项放在检查用户是否已通过身份验证的if块中,如下所示:
<ul>
...
{% if request.user.is_authenticated %}
<li><a href="/logout">Logout</a></li>
{% endif %}
</ul>
虽然使用变量request.user.is_authenticated
是一种方法。 为了更简单地创建 HTML 页面,以便分解登录和注销按钮。
登录后出现的页面应仅包含注销选项/按钮。 这将使您的开发过程更加顺畅。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.