首页 > 解决方案 > 一旦嵌套的if语句在Django模板中为真,如何结束forloop

问题描述

简介-我一个名为应用程序的对象它有许多属性,下面是模型。属性之一是用户。我想看看 request.user 是否在对象用户列表中

我已经尝试在模板中分割forloop多种方式,但都失败了。我只需要循环中的 1 个结果“Do A”“Do B”取决于条件。即使我有一百万个应用程序。但是一旦我收到 3 个应用程序,我就有 2 个 "Do A"或 2 "Do B"|slice:":1"除非我使用错误,否则不起作用。下面是我的代码

{% for app in applications %} #applications is a Application.objects.all()
    {% if applicant.username in app.user.username %} #applicant is request.user The code checks if request.user is a part of objects.users list
        <p> Do A </p>
    {% else %}  
        <p> Do B </p>
    {% endif %}
{% endfor %}

下面是我的模型

class Application(models.Model):
    user = models.ForeignKey(User, related_name='verified')
    applied_on = models.DateTimeField(auto_now_add=True)
    ... # Alot more fields
    token = models.CharField(max_length=350)

标签: djangodjango-templates

解决方案


您在模板中执行了太多逻辑。请在您的视图中尝试此操作(伪代码,因为我不知道您的视图的结构):

applicants = Application.objects.all().values_list('user__username', flat=True) context = {'is_applicant': request.user.username in applicants}

在您的模板中:

if is_applicant:
    something
else:
    something else

推荐阅读