How to use the foreign key in condition html Django

Issue

Anyone know why this condition doesn’t work? In the h4 the lancamento.tipo shows the information "Receita", but the condition does not work. Please help me on this.

lancamento_list.html

    <div class="list-group">
    {% for lancamento in object_list %}
        {% if lancamento.tipo == 'Receita' %}
    <a href="#" class="list-group-item list-group-item-success">
        <h4 class="list-group-item-heading">{{lancamento.tipo}}</h4>
        <p class="list-group-item-text">Descrição: {{lancamento.descricao}}</p>
        <p class="list-group-item-text">Valor: R$ {{lancamento.valor}}</p>
    </a>
        {% else %}
    <a href="#" class="list-group-item list-group-item-danger">
        <h4 class="list-group-item-heading">{{lancamento.tipo}}</h4>
        <p class="list-group-item-text">Descrição: {{lancamento.descricao}}</p>
        <p class="list-group-item-text">Valor: R$ {{lancamento.valor}}</p>
    </a>
        {% endif %}
    {% endfor %}

And the models.py

class Usuario(models.Model):
    nome = models.CharField(max_length=255)
    cpf = models.CharField(max_length=11, unique=True)
    saldo = models.FloatField(default=0)

    def __str__(self):
        return self.nome


class Lancamento(models.Model):
    tipo = models.ForeignKey('Tipo', on_delete=models.CASCADE)
    nome_usuario = models.ForeignKey('Usuario', on_delete=models.CASCADE, default='')
    valor = models.FloatField()
    descricao = models.TextField()
    data_lancamento = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['-data_lancamento']


class Tipo(models.Model):
    nome = models.CharField(max_length=255)

    def __str__(self):
        return self.nome

And the views.py, using the Class Based Views

from django.shortcuts import render
from django.views.generic import ListView
from core.models import Lancamento

# Create your views here.

def index(request):
    return render(request, 'core/index.html')

class LancamentoList(ListView):
    model = Lancamento
    queryset = Lancamento.objects.all()

Solution

Ok, makes more sense now.
Try this out in the template:

{% if lancamento.tipo|stringformat:"s" == 'Receita' %} 

Answered By – Ali

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published