【问题标题】:Why is my else tag in django template not working为什么我在 django 模板中的 else 标签不起作用
【发布时间】:2018-02-13 06:02:40
【问题描述】:

所以我有 manytomany 字段。在模板中我想验证当前用户是否存在于 manytomany 字段中并分别显示输出

模型.py

  class Business(models.Model):
      businessname=models.CharField(max_length=230,null=True)
      creator==models.ForeignKey(User,unique=True)
      users=models.ManyToManyField(Users,null=True,related-name="shared")

在我的 veiw.py 中

def Display(request):
    BusinessObjects = Business.objects.all()
    template="template.html"
    return render(request,template,context={'objects':BusinessObjects})

模板.html

<div class="allobjects">
 {% for obj in objects %}
 {{obj.businessname}}
 <!-- verify if the  current login user exist in the many to many field-->
 {% for currentuser in obj.users %}
  {% if user.username in currentuser.username %}
   <p> You are sharing this object</p>
  {% else %}
  <p> You are not sharing this object

 {% endif %}
 {% endfor %}
 {% endfor %}
</div>

尽管用户名不存在,但我的 else 语句不起作用。但是如果用户名存在,则执行第一个语句。我在 if 语句中做错了什么,为什么我的 else 语句不起作用。谢谢。请不要降级我的问题,如果它对你不重要。

【问题讨论】:

    标签: python html django-models


    【解决方案1】:
    {% if not user in obj.users.all%}
     {% else %}
     {% endif %}
    

    【讨论】:

      【解决方案2】:

      根据 Django 的文档,空值解析为“无”而不是导致错误。所以,可能这两个值都解决了:https://docs.djangoproject.com/en/2.0/ref/templates/language/

      {% if user.username in currentuser.username %}
      

      如果它们都是空的,它应该解析为 true。

      编辑 这里的实际问题是您使用“in”作为比较运算符而不是“==”。如果缺少用户名,您正在检查给定字符串中是否包含空字符串(它是 - 有点像 0 元素是任何元素集的子集)。

      如果你想过滤掉空字符串,你可以使用长度标签。来自docs

      length¶
      Returns the length of the value. This works for both strings and lists.
      
      For example:
      
      {{ value|length }}
      If value is ['a', 'b', 'c', 'd'] or "abcd", the output will be 4.
      
      The filter returns 0 for an undefined variable.
      
      {% if user.username|length > 0 %}
      

      【讨论】:

      • 那么解决方法和正确的方法是什么?
      • 啊,这是因为您使用的是“in”而不是“==”。从技术上讲,“空字符串”总是包含在字符串“内”。
      猜你喜欢
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 2016-03-22
      • 1970-01-01
      • 2020-01-01
      相关资源
      最近更新 更多