Django将数据从两个模型传递到模板

时间:2014-07-17 20:17:42

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

我有这个问题,非常愚蠢但很好......我有两个模型:

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'),

谁能告诉我怎么能这样做呢。显然我的代码有问题,所以我很感激帮助。提前谢谢

2 个答案:

答案 0 :(得分:2)

试试这个

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)

答案 1 :(得分:1)

问题是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)