【问题标题】:Django, display certain hyperlinks based on user groupDjango,根据用户组显示某些超链接
【发布时间】:2020-03-24 13:11:52
【问题描述】:
{% extends 'base.html' %}

{% block content %}
  <p>Welcome to home page.</p>
  <p>{% user.groups.all() %}</p>
{% endblock %}

目前我正试图弄清楚如何才能让所有用户的组都显示在页面上。这会导致错误......第 5 行的块标记无效:'user.groups.all()',预期为 'endblock'。您是否忘记注册或加载此标签?

我尝试过执行 if 语句,但它似乎一旦满足一个条件就会中断。例如,如果用户是 test1 和 test2 组的一部分,我希望它显示 test1 和 test2,但它只显示 test1。

{% extends 'base.html' %}

{% block content %}
  <p>Welcome to home page.</p>
  {% if user.groups.all.0.name == "test1" %} 
  <p>test1</p>
  {% if user.groups.all.0.name == "test2" %}
  <p>test2</p>
  {% endif %}
{% endblock %}

【问题讨论】:

    标签: html django templates


    【解决方案1】:

    在第一个代码中,您应该改用{{ }}。要访问组,请执行以下操作:

     {{ user.groups.all }}
    

    并检查特定组:

    {% if desired_group in user.groups.all %}
      some html..
    {% endif %}
    

    如果要为每个组输出特定的 html:

    {% for group in user.groups.all %}
       {% if group == desired_group %}
         some html..
      {% endif %}
       ..some more conditions..
    {% endfor %}
    

    【讨论】:

    • 我对第 2 块和第 3 块的工作方式有点困惑。我想我正在倒退。所以如果用户有“这些组”,则显示这些组。但我相信第二和第三块正在做别的事情?或者它是打算那样..
    • 我不明白你的目的是什么,但是如果你想直接输出组,你可以在for循环中使用{{ group }}。
    • 哦,我想我现在明白了。出于某种原因,我认为 user.groups.all 会获取表中的所有组,但它获取的是与 user 相关的所有组。非常感谢
    • 是的,如果您想获取所有可用的组,您可以使用上下文处理器或将组作为视图中的上下文传递。
    • 知道为什么第三个块在我的情况下不起作用吗?不输出任何html代码,也没有错误..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 2012-08-18
    相关资源
    最近更新 更多