django - 一旦嵌套的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)
解决方案
您在模板中执行了太多逻辑。请在您的视图中尝试此操作(伪代码,因为我不知道您的视图的结构):
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
推荐阅读
- angular - Angular variable shared to various services and components
- python - My code returns one correct review and NULL instead of the other reviews
- react-native - Network call from native module instead from Javascript/React Native
- mysql - 在 TRIGGER 中使用 INFORMATION_SCHEMA.COLUMNS 记录对 _all_ 列的更改?
- groovy - How to compare values in groovy
- javascript - Javascript convert date and time today and save .txt file using its format
- java - TarsosDSP pitch shifting artifacts
- java - CriteriaBuilder - Debug - NamedParameterDescriptor and query.getParameters() - Console IDE / log - Show name parameters and values
- c - Embedded system: How to identify required tasks/threads?
- oracle - Oracle HCM 云 API - 按 HireDate 获取员工