I am using ListView to list some objects from a model. I want to highlight entries in the displayed list where the listed item was created by the current user, and I plan to do this with a small coloured dot (circle) created using CSS. Here's a test case.
# 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> </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>
For a bunch of reasons I need to do this in the CBV rather than annotate objects in the model.
How can I add an attribute to the objects in the context object_list? Alternatively, how can I pass a list to my template?
Thanks and regards...Paul