繁体   English   中英

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

[英]Django passing data from two models to a template

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

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

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

尝试这个

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不是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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM