Search code examples
pythonhtmldjangolistdjango-class-based-views

How to use the foreign key in condition html Django


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' %}