i have listview class like this :
class VechileListView(ListView):
model = Vechile
template_name = 'store/arm_list.html'
context_object_name = 'arm'
in model Vechile
, there are field tanggal_stnk
it work fine, now the problem i want to marked red some data in tanggal_stnk
here are the template :
{% if arm %}
{% for data in arm %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ data.tanggal_stnk }}</td>
.......
tanggal_stnk
is a datefield
, for example i want to mark text to red color, if the date is today..
what i already try to add something like this in Class VechileListView
class VechileListView(ListView):
model = Vechile
template_name = 'store/arm_list.html'
context_object_name = 'arm'
def expiry(request):
expired_stnk = Vechile.objects.filter(tanggal_stnk = datetime.now())
context = {
'expired_stnk' : expired_stnk
}
return render(request, 'store/arm_list.html', context)
is it possible in listView, and how to implement it on the template, Thanks
You can annotate the queryset with a boolean that specifies if it expires today:
from django.db.models import BooleanField, ExpressionWrapper, Q
from django.utils.timezone import now
class VechileListView(ListView):
model = Vechile
template_name = 'store/arm_list.html'
context_object_name = 'arm'
def get_queryset(request):
return Vechile.objects.annotate(
expires_today=ExpressionWrapper(
Q(tanggal_stnk=now().date()),
output_field=BooleanField()
)
)
then we render it with:
{% for data in arm %}
<tr>
<td>{{ forloop.counter }}</td>
<td{% if data.expires_today %} style="color:#0000ff"{% endif %}>{{ data.tanggal_stnk }}</td>
</tr>
{% endfor %}