Customize Cell Coloring Based on Criteria in Django HTML

I am facing a situation where I need to change the background color of certain cells in an HTML table based on their values. Here is an image of the table structure created using Django views and populated with data from a loop. The CSS and HTML code snippets can be found below. Essentially, I aim to have specific cell backgrounds change to different colors when the value within them meets a certain criteria. Thank you for your assistance.

<div class="table-responsive">
    <table class="table" id="scores">
        <thead>
            <tr>
                <td rowspan="3"></td>
                <th colspan="3" scope="colgroup">Reasoning</th>
                <th colspan="3" scope="colgroup">Executive Functions</th>
                <th colspan="2" scope="colgroup">Speed</th>
                <th colspan="2" scope="colgroup">Memory</th>
            </tr>
            <tr>
                <th scope="col">Verbal</th>
                <th scope="col">Spatial</th>
                <th scope="col">Abstract</th>
                <th scope="col">Flexible</th>
                <th scope="col">Working Memory</th>
                <th scope="col">Attention</th>
                <th scope="col">Processing</th>
                <th scope="col">Visual Motor</th>
                <th scope="col">Verbal</th>
                <th scope="col">Visual </th>
            </tr>
        </thead>
        {% for i in scores %}
            <tbody>
                <tr>
                    <td>{{i.test_date}}</td>
                    <td>{{i.reasoning_verbal }}</td>
                    <td>{{i.reasoning_spatial}}</td>
                    <td>{{i.reasoning_abstract}}</td>
                    <td>{{i.executive_flexibility}}</td>
                    <td>{{i.executive_working_memory}}</td>
                    <td>{{i.executive_attention}}</td>
                    <td>{{i.speed_processing}}</td>
                    <td>{{i.speed_visual_motor}}</td>
                    <td>{{i.memory_verbal}}</td>
                    <td>{{i.memory_visual}}</td>
                </tr>
            </tbody>
        {% endfor %}
    </table>
</div>
#d6
{
    background-color: rgb(1, 109, 167);
    color: black;
}
#d5
{
    background-color: rgb(1, 167, 164);
    color: black;
}
#d4
{
    background-color: rgb(154, 191, 80);
    color: black;
}
#d3
{
    background-color: rgb(228, 190, 36);
    color: black;
}
#d2
{
    background-color: rgb(214, 142, 33);
    color: black;
}
#d1
{
    background-color: rgb(187, 185, 182);
    color: black;
}

https://i.sstatic.net/xL8sj.jpg

Answer №1

Seems like you are utilizing bootstrap in your project. Here's a sample code snippet with a bootstrap class, although creating your own custom class is just as feasible.

Incorporating Django's template language into your HTML tags can be done like this:

<td class="{% if i.your_var == 6 %}table-warning{% endif %}">{{i.your_var}}</td>

If the value of the variable is 6, the cell will appear orange (as a warning). For various scenarios or different types and ranges of variables, it's advisable to create a custom filter tag:

{% load my_color_filter %}

<td class="{{i.your_var|my_color_filter}}">{{i.your_var}}</td>

Here's an example of `my_color_filter.py`:

from django import template
register = template.Library()

@register.filter()
def my_color_filter(my_var):
    if my_var == 6:
        td_class = 'someClass'
    elif my_var > 6:
        td_class = 'someOtherClass'
    # Add more conditions as needed...

    return td_class

To delve deeper into custom filter tags, visit this section of the Django Docs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Share JSON data across functions by calling a function

I am currently working on a project where I need to load JSON using a JavaScript function and then make the loaded JSON objects accessible to other functions in the same namespace. However, I have encountered some difficulties in achieving this. Even after ...

Getting data before the Router is loaded following authentication with Angular 2+ - A comprehensive guide

I'm hoping this isn't a repeat. Within my login component, I have a feature that allows users to log in, which calls a service and retrieves a Token. Upon successful login, the token is saved to localStorage. Subsequently, I use the getUserData ...

Analyzing data from radio button selections using React Hooks calculations

My goal is to calculate the total price based on user inputted values. The total price depends on "ToppingPrice", "Size", and "Qty". Currently, my code is not calculating the total price correctly as I am still learning React. const [quantity, setQuantit ...

What is the process for modifying the value of a concatenated string?

I have a scenario where I need to extract the date of a blog post from one page on a website and display it on another page within the same site. Initially, the date is shown as 2/22/18 on the first page. With the jQuery code provided below, I am able to ...

What are the best practices for integrating RxJS into Angular 2 projects?

How can I write code like this in Angular 2? var closeButton1 = document.querySelector('.close1'); var close1ClickStream = Rx.Observable.fromEvent(closeButton1, 'click'); I have attempted various methods to incorporate this into an An ...

Outline a table element without altering the dimensions of the cell

When creating a diagram in an HTML table, I encountered a challenge. The TD elements have fixed dimensions, and I wanted to highlight this div with a border or circle. However, when I attempted to do so using CSS, it deformed the div. I couldn't use ...

Determine the central point of the cluster with the most concentrated xy data points

In my project, I have a 200 x 200 square grid where users can vote on the next desired position of an object within this space. Each time a user submits their vote, the XY position is added to an array. Currently, to determine the "winning" position, I ca ...

My wish is for the animation to activate when hovering over an "a" element on the progress bar

Below is the HTML and CSS code: .collection-by-brand { position: relative; display: flex; width: 100%; height: auto; justify-content: space-around; flex-wrap: wrap; background: linear-gradient(to bottom, #ffffff, whitesmoke); margin-bo ...

Designing two stacked divs below two adjacent divs

Struggling to figure out how to achieve a simple alignment: I want a line with 2 side by side divs, the first one taking up its necessary space and the second occupying the remaining space (this part is easy with inline-block or float) The right div shou ...

Making jquery's one() function work effectively with duplicated classes

Take a look at the following HTML code snippet: <div class="options-selecter"> <span class="item-option" data-value="8">XYZ</span> <span class="item-option" data-value="11">LMN</span> <span class="item-option a ...

Is there a "Read more" link to expand the content on the page?

I am struggling to figure out why my JavaScript code for toggling between showing more text and less text is not functioning correctly. My goal is for the user to click on the "Show More" button to reveal additional text, and then be able to click on "Show ...

Struggling to display Firebase Auth information resulting in 'undefined' value within React web application

When loading a user's profile page, I am trying to display their displayName and email information retrieved from Firebase Auth. I have implemented this logic within the 'componentDidMount' method by updating the state with the response dat ...

The data list is failing to retain previous elements as new ones are incorporated

I have a list for uploads, and whenever I upload new data, the old data in the list gets removed. However, I want to display all the data together. How can I resolve this issue? const [fileList, setFileList] = useState<AddedFile[]>([]); const beg ...

Guidelines for ensuring that a radio button must be chosen prior to submission

I'm struggling with implementing AngularJS validation for a set of questions with radio answer choices. I want to ensure that the user selects an answer before moving on to the next question by clicking "Next". Check out my code below: EDIT: Please k ...

Shifting Objects within Bootstrap 5 Navigation Menu

Hey there! I'm having some trouble aligning the items in a Bootstrap 5 navigation bar to the side, just like in this screenshot: https://i.sstatic.net/nxh80.png I tried adjusting the alignment but nothing changed on the site (I was using Live Server ...

I am struggling to make Angular Charts display labels the way I want them to

Struggling to customize an angular chart for my project. The x axis should display dates and the mouse over should show client names, all retrieved from an array of resource objects in a loop. The loop code snippet is as follows: angular.forEach(charts, ...

Switch up the initial caret position in a Bootstrap 4 dropdown

This task seems trickier than I expected. I am trying to create a Bootstrap dropdown list where the caret initially points to the right and then rotates downward when expanded. Rotating the caret is not the problem, but starting with it facing right is cha ...

Is the functionality of the jquery trigger('resize') limited to only one instance?

Here are two code snippets that I have: function adjustFooter() { var wrapper = $('#disqus_wrapper').height(); if ( wrapper > 200 ) { $(window).trigger('resize'); } }; var element = $('#disqus_wrapper&apos ...

Tips for stopping a drop-down box from changing its size

Currently working with C# and jquery. I've implemented a dropdown box containing 20 elements, each sized according to the largest element's text length. In addition, there is a checkbox that, when clicked by the user, removes all selections from ...

Vue failing to update when a computed prop changes

As I work with the Vue composition API in one of my components, I encountered an issue where a component doesn't display the correct rendered value when a computed property changes. Strangely, when I directly pass the prop to the component's rend ...