【问题标题】:working with {% if %} {% else %} in Django在 Django 中使用 {% if %} {% else %}
【发布时间】:2019-12-03 16:00:04
【问题描述】:

如何使用 If-Statement 从登录页面隐藏用户名。 我使用此代码在登录后在主页中显示用户名,并且它正在工作

{%if request.user.first_name%}{{request.user.first_name}}{%else%}{{user}}{%endif%}

但问题是它在登录页面中也显示为“AnonymousUser”。我该如何隐藏这个

有什么想法吗?

【问题讨论】:

    标签: python html django


    【解决方案1】:

    首先,您应该检查用户是否已通过身份验证,如果已通过身份验证,则显示 first_name 或用户名,否则只需提供登录和注册链接。

    {% if user.is_authenticated %}
       {%if request.user.first_name%}
          {{request.user.first_name}}
       {%else%}
          {{request.user.username}}
       {%endif%}
    {% else %}
      <a href="" >login</a>
      <a href="" >Signup</a>
    {% endif %}
    

    【讨论】:

      【解决方案2】:

      看看这个:

      {% if user.is_authenticated %}{% endif %}
      

      相关: How to check if a user is logged in (how to properly use user.is_authenticated)?

      【讨论】:

        【解决方案3】:

        您可以在这里使用.is_authenticated [Django-doc]

        {% if request.user.<b>is_authenticated</b> %} ... {% endif %}

        对于未通过身份验证的用户(如AnonymousUser),检查将失败。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-10-12
          • 1970-01-01
          • 2022-01-25
          • 1970-01-01
          • 2019-04-25
          • 1970-01-01
          相关资源
          最近更新 更多