Getting context from database for views

Question:

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 class="no" >{{purchase.product}}</td>
    <td class="qty" >{{purchase.quantity}}</td>
    <td class="total" >${{purchase.product.price}}</td>
  </tr>
  {% endfor %}
</tbody>
Asked By: Sesshōmaru

||

Answers:

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

Answered By: StefanoTrv

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

Answered By: Delton
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.