[Answered ]-Change the rows with the same cell value in the same color in HTML table – Django project

1👍

Everything we want to pass as context, we should keep inside view we want to use it in. It’s more readable when we have more and more code.

What we are going to do, it’s define a color for numbers 0-9. I’ll pick some light colors for now, you can change them as you prefer.

views.py:

def table2022(request):
    mylist = sheet_instance.get_all_records()
    colors = {'0': 'aqua', '1': 'beige', '2': 'burlywood', '3': 'lightgrey', '4': 'silver', '5': 'skyblue', '6': 'lightblue', '7': 'lightpink', '8': 'lightgreen', '9': 'lawngreen'}
    context = {'mylist': mylist, 'colors': colors}

    return render(request, 'table2022.html', context)

Now, because in templates it’s not that simple to use Python, we need to create custom Template Tag. Let’s start with creating folder in your app, let’s name it custom_tags.py. It should be created in YourProject/your_app/templatetags/ folder, so we have to also create templatetags folder in there.

custom_tags.py:

from django import template

register = template.Library()

@register.filter(name='get_color')
def get_color(colors, number):
    return colors[str(number)[-1]]

your_template.html:

{% load custom_tags %}

...

{% for element in mylist %}
    <tr>
        <td>{{ element.StartDate }}</td>
        <td style="background-color: {{ colors|get_color:element.ID }}">
            {{ element.ID }}
        </td>
        <td>{{ element.Receiver }}</td>
        <td>{{ element.Days }}</td>
    </tr>
{% endfor %}

get_color tag is basically taking whole ID, then extract only last number and make it a string. After that it uses the single number as a key in colors dictionary and passes corresponding value to template, where it is going to be a valid html color.

Custom tags are used to ‘implement’ some Pythonic code directly into template. Don’t use it too much, because most of coding should be in standard files like views.py and models.py. But sometimes there is no better way. 🙂

For more details about Tags, check that Django’s DOCS

Leave a comment