Pretty much a Django any Python noob - been studying for a month or so and watching tutorials...so I know enough to be dangerous. I'm trying to randomize the CSS class in an HTML template. I'm using a custom Bootstrap template to display database entries as cards, and I want to randomize the background. I've got the basics down, but haven't been able to figure out how to randomize the CSS class value in the actual html template.
I've tried the randomizing the value in the relevant Django views template. Searched through 2.2 docs, stack, google, etc., but so far no joy
views.py:
import random
from django.shortcuts import render
from compliments.models import Compliments
def compliment(request):
compliment = Compliments.objects.all()
return render(request, 'compliments/home.html', {'compliment': compliment})
classList = [
'bg-secondary', 'bg-success', 'bg-danger', 'bg-warning',
'bg-info', 'bg-light', 'bg-dark'
]
css_class = random.choice(classList)
my HTML:
{% extends 'base.html' %}
{% block body %}
<div class="row">
<div class="col-12">
<h4 class="mb-4">Compliments</h4>
</div> <!-- end col -->
</div><!-- end row -->
<div class="row">
{% for compliment in compliment %}
<div class="col-md-4">
<div class="card {{ compliment.css_class }} text-white">
<div class="card-body">
<p class="card-text">{{ compliment.body }}</p>
<a href="javascript: void(0);" class="btn btn-primary btn-sm">Select</a>
</div> <!-- end card-body-->
</div> <!-- end card-->
</div> <!-- end col-->
{% endfor %}
</div>
{% endblock%}
I was expecting that I could get "css_class" from my views to show up in the HTML template at {{ complment.css_class }}, but inspecting the class attributes show that it is not being rendered at all (just blank).
for compliment in complimentrename either of the two.