gpt4 book ai didi

Django ListView : How can I create a conditional attribute that's accessible in my template?

转载 作者:行者123 更新时间:2023-12-04 09:15:27 25 4
gpt4 key购买 nike

我正在使用 ListView 列出模型中的一些对象。我想高亮显示列表中的条目,其中列出的项目是由当前用户创建的,我打算用一个使用 CSS 创建的小彩色圆点(圆圈)来做到这一点。这是一个测试用例。

# models.py

from django.db import models
from django.contrib.auth.models import User

class Foo(models.Model):
created_by = models.ForeignKey(
User,
to_field='username',
on_delete=models.PROTECT,
related_name='foos_as_usernames',
blank=False
)
stuff = models.CharField(max_length=128, blank=True)
#views.py

from django.views.generic import ListView

class FooListView(ListView):
model = Foo

def get_context_data(self, **kwargs):
context = super(FooListView, self).get_context_data(**kwargs)

# Here I want to conditionally set a dot_class attribute based on
# comparing Foo.created_by with the current user, i.e.
# if object.created_by == user:
# object.dot_class = 'its-me'
# What do I add here to create the dot_class attribute in the object_list?
# Is there some other way I can pass a list to the foo_list.html template?

return context

# foo_list.html

{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>FooBar</title>
<style>
.its-me { height: 8px; width: 8px; background-color: dodgerblue; border-radius: 50%; display: inline-block; }
</style>
</head>
<body>
<table>
<tr>
<th>&nbsp;</th>
<th>Stuff</th>
</tr>
{% for obj in object_list %}
<tr>
<td><span class="{{ obj.dot_class }}"></span></td>
<td>{{ obj.stuff }}</td>
</tr>
{% endfor %}
</table>
</body>

出于多种原因,我需要在 CBV 中执行此操作,而不是在模型中注释对象。
如何向上下文 object_list 中的对象添加属性?
或者,如何将列表传递给我的模板?
谢谢和问候...保罗

最佳答案

如果您想作为变量模板发送,请尝试这种方式:

def get_context_data(self, **kwargs):
context = super(FooListView, self).get_context_data(**kwargs)
foo_list = context['foo_list']
for object in foo_list:
if object.created_by == self.request.user:
foo.dot_class = 'its-me'
foo.save()
context['foo_list'] = foo_list
return context
那么你可以直接在模板中使用它:
<td><span class="{{obj.dot_class}}"></span></td>

关于Django ListView : How can I create a conditional attribute that's accessible in my template?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63248357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com