我想更改导航栏中的登录链接并显示已登录用户的用户名,请帮助我如何实现。不太确定在模板中的何处添加逻辑语句
views.py
def login_request(request):
if request.method == "POST":
user_form = AuthenticationForm(request, data=request.POST)
if user_form.is_valid():
username = user_form.cleaned_data.get("username")
password = user_form.cleaned_data.get("password")
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect("loststuffapp:IndexView")
else:
messages.error(request, "Invalid username or password")
user_form = AuthenticationForm()
return render(request,
"loststuffapp/login.html",
{"user_form":user_form})
login.html
{% extends "loststuffapp/base.html" %}
{% block content %}
<form method="POST">
{% csrf_token %}
{{user_form.as_p}}
<p><button class="btn" type="submit" >Login</button></p>
<p>If you don't have an account, <a href="/register
<strong>register</strong></a> instead</p>
{% endblock %}
我的导航栏代码
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li>
<form action="{% url 'loststuffapp:IndexView' %}" method="get">
<input name="q" type="text" placeholder="Search..." value="{{request.GET.q}}">
</form>
</li>
{% if request.user.is_authenticated %}
{{user.username}}
{% endif %}
<li><a href="/login">Login</a></li>
<li><a href="/register">Register</a></li>
<li><a href="/logout">Logout</a></li>
</ul>
答案 0 :(得分:2)
如果要在模板中显示登录用户的用户名,则可以这样:
{% if user.is_authenticated %}
{{user.username}}
{% endif %}
如果您希望用户身份验证后登录链接消失,那么您可以这样做:
{% if not user.is_authenticated %}
<li><a href="/login">Login</a></li>
{% endif %}
为了更好地验证用户身份,您只提供注销链接,并删除其他链接
{% if user.is_authenticated %}
{{user.username}}
<li><a href="/logout">Logout</a></li>
{% else %}
<li><a href="/login">Login/a></li>
<li><a href="/register">Register</a></li>
{% endif %}