Home > OS >  How to use the foreign key in condition html Django
How to use the foreign key in condition html Django

Time:06-09

I'm a beginner in Python and I have this question.

Anyone know why this condition dont 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 >
    {% for lancamento in object_list %}
        {% if lancamento.tipo == 'Receita' %}
    <a href="#" >
        <h4 >{{lancamento.tipo}}</h4>
        <p >Descrição: {{lancamento.descricao}}</p>
        <p >Valor: R$ {{lancamento.valor}}</p>
    </a>
        {% else %}
    <a href="#" >
        <h4 >{{lancamento.tipo}}</h4>
        <p >Descrição: {{lancamento.descricao}}</p>
        <p >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()

CodePudding user response:

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

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