首页 > 解决方案 > Django为不同的组模板不同的项目。用户身份验证和组隔离

问题描述

因此,我正在尝试制作一个像网站一样的教室,但这仅适用于我认识的人正在运行的课程。我希望不同的群体对网站有不同的看法。例如组“Guest”看不到菜单项组“Student”可以看到。但它不是很有效......这是我的一些菜单代码:

      {% if user.is_authenticated %}

      {% for group in user.groups.all %}

      {% ifequal group.name 'Student' %}

      <div class="menu">
          <button onclick="location.href='http://10.0.0.60:8000/';" class="home en">Home</button>

        <button onclick="location.href='http://10.0.0.60:8000/news';" class="news en">News</button>

        <button onclick="location.href='http://10.0.0.60:8000/about';" class="about en">About us</button>

          <button onclick="location.href='http://10.0.0.60:8000/lessons';" class="home en">Lessons</button>

          <button onclick="location.href='http://10.0.0.60:8000/assignments';" class="home en">Assignments</button>

      </div>

      {% endifequal %}

      {%ifequal group.name 'Guest'%}

        <button onclick="location.href='http://10.0.0.60:8000/';" class="home en">Home</button>

        <button onclick="location.href='http://10.0.0.60:8000/news';" class="news en">News</button>

        <button onclick="location.href='http://10.0.0.60:8000/about';" class="about en">About us</button>

      {%endifequal%}

      {%endfor%}

      {%else%}

      <div class="menu">
          <button onclick="location.href='http://10.0.0.60:8000/';" class="home en">Home</button>

        <button onclick="location.href='http://10.0.0.60:8000/news';" class="news en">News</button>

        <button onclick="location.href='http://10.0.0.60:8000/about';" class="about en">About us</button>
      </div>

      {%endif%}

但上面也引发了一个错误。

TemplateSyntaxError at /assignments
Unexpected end of expression in if tag.

以下是有关该错误的更多信息:

Request Method: GET
Request URL:    http://10.0.0.60:8000/assignments
Django Version: 3.2.7
Exception Type: TemplateSyntaxError
Exception Value:    
Unexpected end of expression in if tag.
Exception Location: /home/*****/.local/lib/python3.9/site-packages/django/template/smartif.py, line 144, in nud
Python Executable:  /usr/bin/python3
Python Version: 3.9.5

标签: javascriptpythonhtmldjangodjango-templates

解决方案


这是如何做到的。我不知道为什么这行得通,而上面的那个不行,但它就是这样。但我认为你必须指定每个条件而不是使用 else

代码:

{% if user.is_authenticated %}

      {% for group in user.groups.all %}

      {% ifequal group.name 'Student' %}

      <div class="menu">
          "items for group student"

      </div>

      {% endifequal %}

      {%ifequal group.name 'Guest'%}

        <div class="menu">
          "items for group Guest"
      </div>

      {%endifequal%}

      {%endfor%}

      {%elif not user.is_authenticated%}

      <div class="menu">
          "items for anonymous users"
      </div>

      {%endif%}


推荐阅读