【问题标题】:Django passing data from two models to a templateDjango 将数据从两个模型传递到模板
【发布时间】:2014-07-17 20:17:42
【问题描述】:

我有这个问题,很傻但是很好......我有这两个模型:

class Cliente(models.Model):
CUIT = models.CharField(max_length=50)
Direccion = models.CharField(max_length=100)
Razon_Social = models.CharField(max_length=100)

def __unicode__(self):
    return self.Razon_Social

class Factura(models.Model):
TIPO_FACTURA = (
    ('A', 'A'),
    ('E', 'E')
    )
tipo_Factura = models.CharField(max_length=1, choices= TIPO_FACTURA)
nombre_cliente = models.ForeignKey(Cliente)
fecha_factura = models.DateField()
IRI = models.IntegerField()
numero_De_Factura = models.IntegerField(max_length=50)
descripcion = models.CharField(max_length=140)
importe_Total= models.FloatField()
importe_sin_iva = models.FloatField()

def __unicode__(self):
    return "%s - %s" % (unicode(self.nombre_cliente), self.numero_De_Factura)

我列出了每个客户的账单,当用户点击它时,我想显示一些关于账单的信息(西班牙语中的 Factura)和一些关于客户的信息,比如它的地址

这是我的views.py:

def verFactura(request, id_factura):
    fact = Factura.objects.get(pk = id_factura)
    cliente = Cliente.objects.filter(factura = fact)
    template = 'verfacturas.html'
    return render_to_response(template, locals())

我正在尝试获取此特定账单的客户信息,以便显示其信息,但在模板中我看不到任何内容:

<div >
   <p>{{fact.tipo_Factura}}</p>
   <p>{{fact.nombre_cliente}}</p>
   <p>{{cliente.Direccion}}</p>
</div><!-- /.box-body -->

这是我的网址:

url(r'^verFactura/(\d+)$', 'apps.Administracion.views.verFactura',name = 'verFactura'),

谁能告诉我我该怎么做。显然我的代码有问题,所以我将不胜感激。提前谢谢你

【问题讨论】:

  • 能否正确格式化您的代码?
  • 谢谢丹尼尔。对此感到抱歉

标签: python django templates django-views django-urls


【解决方案1】:

试试这个

def verFactura(request, id_factura):
    fact = Factura.objects.get(pk = id_factura)
    cliente = Cliente.objects.filter(factura = fact)
    template = 'verfacturas.html'

    extra_context = dict()
    extra_context['fact'] = fact
    extra_context['cliente'] = cliente

    return render_to_response(template, extra_context)

【讨论】:

  • 你好。我在我的模板中使用了这个标签:

    {{cliente.Direccion}}

    并且没有任何返回。这是获取客户地址的正确方法吗?我用你建议的代码修复了我的views.py。谢谢
  • 是的,这是正确的方法。 local()extra_context 正在做的是传递可以在模板中使用的键值对字典。你能检查一下你的客户对象在视图中是否不是 None 吗?
【解决方案2】:

问题在于cliente 不是Cliente 实例,而是实例的查询集。每个factura只有一个cliente,所以你可以这样做:

def verFactura(request, id_factura):
    fact = Factura.objects.get(pk = id_factura)
    cliente = Cliente.objects.get(factura = fact) # use `get` instead of `filter`
    template = 'verfacturas.html'

    extra_context = dict()
    extra_context['fact'] = fact
    extra_context['cliente'] = cliente

    return render_to_response(template, extra_context)

【讨论】:

    猜你喜欢
    • 2015-11-15
    • 2021-01-31
    • 2020-03-19
    • 2019-02-16
    • 2016-11-17
    • 2023-01-16
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    相关资源
    最近更新 更多