【问题标题】:How to use the foreign key in condition html Django如何在条件html Django中使用外键
【发布时间】:2022-06-11 00:38:20
【问题描述】:

有人知道为什么这种情况不起作用吗?在 h4 中,lan​​camento.tipo 显示信息“Receita”,但条件不起作用。请帮我解决这个问题。

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

还有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

还有views.py,使用基于类的视图

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()

【问题讨论】:

    标签: python html django list django-class-based-views


    【解决方案1】:

    好的,现在更有意义了。 在模板中试试这个:

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

    【讨论】:

    • 感谢您的回答,但在项目中这个名称是正确的 'lancamento_list.html',我在 stackoverflow 的帖子中输入了错误的名称。问题出在 {% if lancamento.tipo == 'Receita' %} return false 但在

      中显示 'Receita' 我不知道为什么,我需要检查此条件以自定义 h4。

    • 我已经编辑了答案。希望它对你有用
    • 现在开始工作了!谢谢你的帮助,你能解释一下为什么以前不工作吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2021-01-26
    • 2010-10-27
    • 1970-01-01
    • 2018-12-12
    • 2021-01-24
    • 1970-01-01
    相关资源
    最近更新 更多