Search code examples
djangodjango-templatesunsigneddjango-template-filters

I'm creating a table and am coloring the text green or red depending of + or - value, is there a way I can remove the sign from the number


I am trying to remove the '- 'sign from my number when it displays in html because I don't need it any more as I have color coded the text instead. Is this possible and if so how could I remove the - sign if there is one ?

Table loop below

{% for sale in page_obj %}
            <tr>
                <td>{{sale.transaction.currency}}</td>
                <td>{{sale.amount_sold}}</td>
                <td>{{sale.amount_per_coin_sold}}</td>
                <td>{{sale.total_price_sold}}</td>
                <td>{{sale.transaction.amount_per_coin}}</td>
                <td>{{sale.date_sold|date:"j N Y"}}</td>
                {% if sale.profit_loss < 0 %}
                    <td style = "color:red">{{ sale.profit_loss }}</td>
                {% else %}
                <td style = "color:green">{{ sale.profit_loss }}</td>
                {% endif %}  
                {% if sale.profit_loss_percent < 0 %}
                <td style = "color:red">{{sale.profit_loss_percent}}</td>
                {% else %}
                <td style = "color:green">{{sale.profit_loss_percent}}</td>
                {% endif %}
                 <td><a href="{% url 'sale-detail' sale.id %}">View</a></td>
            </tr>
            {% endfor %}

Solution

  • You can create a new function inside your model like:

    def get_absolute_profit_loss(self):
        return abs(self.profit_loss)
    

    And then inside the template you can do this:

    {% if sale.profit_loss < 0 %}
         <td style = "color:red">{{ sale.get_absolute_profit_loss }}</td>
    {% else %}
         <td style = "color:green">{{ sale.profit_loss }}</td>
    {% endif %}