I want to display this context inside an invoice html page but I seem to be stuck at getting data. I want this data to be displayed at the invoice page. Currently, it is giving me Error:''QuerySet' object has no attribute 'product''
models.py:
class PurchaseItem(models.Model):
product = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.PositiveSmallIntegerField()
purchase_price = models.DecimalField(max_digits=6, decimal_places=2)
paid_amount = models.DecimalField(max_digits=6, decimal_places=2)
views.py:
def get_context_data(request, **kwargs):
purchases = PurchaseItem.objects.all()
context={
"company": {
"name": "Mc-Services",
"address": "1080, Vienna, Austria",
"phone": "(818) XXX XXXX",
"email": "[email protected]",
'product': purchases.product,
'price' : purchases.product.price,
'quantity' : purchases.quantity,
}}
return render(request, 'purchase/pdf_template.html', context)
and the html file
pdf_template.html:
<tbody>
{% for purchase in purchases %}
<tr>
<td >{{purchase.product}}</td>
<td >{{purchase.quantity}}</td>
<td >${{purchase.product.price}}</td>
</tr>
{% endfor %}
</tbody>
CodePudding user response:
Here's the error: purchases = PurchaseItem.objects.all()
In your code purchases
is the set of all the purchases, but then you try to use it as if it was a single purchase. You need to take one single element from the set. For example, if you wanted the newest item you could use purchases = PurchaseItem.objects.last.()
.
CodePudding user response:
you might have to do something like this
def get_context_data(request, **kwargs):
purchases = PurchaseItem.objects.all()
context={
"company": {
"name": "Mc-Services",
"address": "1080, Vienna, Austria",
"phone": "(818) XXX XXXX",
"email": "[email protected]",
'purchases': purchases,
}}
return render(request, 'purchase/pdf_template.html', context)
and then use the same HTML template to display all your purchases