How to display data from a serializer that uses foriegnkey of other table in Drf to HTML templates?

Viewed 35

I am using drf serializer in a APIView to display data in a template like cart data and list of all item in database.

One of them uses the ```foreign Key`` of other. I have tried every single way but couldn't find any solution

here is my models.py


class Item(models.Model):
    TYPE = [('REGULAR', 'Regular'), ('SPICY', 'Spicy')]
    item_type = models.CharField(max_length=7, choices=TYPE)
    image = models.ImageField(upload_to="menu")
    name = models.CharField(max_length=256)
    description = models.TextField(max_length=500)
    price = models.FloatField()

    def __str__(self):
        return f"{self.name}"


class OrderItem(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)


    def __str__(self):
        return self.item.name

    @property
    def get_item_cost(self):
        item_cost = self.item.price
        return item_cost

Here is the serializer'

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model= Item
        fields= "__all__"

class OrderItemSerializer(serializers.ModelSerializer):
    class Meta:
        model= OrderItem
        fields= "__all__"

and here is the html template

class MenuView(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'menu.html'
    permission_classes = (AllowAny,)

    def get(self, request):
        query = Item.objects.all()
        queryset = OrderItem.objects.all()
        serializer_item = ItemSerializer(query, many=True)
        serializer = OrderItemSerializer(queryset, many=True)
        item= {'data': serializer_item.data, 'cart': serializer.data}
        return Response({'item': item})

Its working perfectly fine till this part after that I am unable to retrieve the data in template, template is empty.


<div class="modal fade" id="cartModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header border-bottom-0">
        <h5 class="modal-title" id="exampleModalLabel">
          Your Cart
        </h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <table class="table table-image">
          <thead>
            <tr>
              <th scope="col">Image</th>
              <th scope="col">Food Item</th>
              <th scope="col">Price</th>
              <th scope="col">Item Type</th>
              <th scope="col">Actions</th>
            </tr>
          </thead>
          <tbody>
            {% if item %}
            {% for c in item %}
            <tr>
              <td class="w-25">
                <img src="{{c.item.image}}"
                  class="img-fluid img-thumbnail" alt="Sheep">
              </td>
              <td>{{c.cart.item.id}}</td>
              <td>{{c.cart.item.price}}</td>
              <td>{{c.cart.item.type}}</td>
              <td>
                <a id="{{c.item.id}}" onclick="deleteitem(this.id)" class="btn btn-danger btn-sm">
                  <i class="fa fa-times"></i>
                </a>
              </td>
            </tr>
            {% endfor %}
            {% endif %}
          </tbody>
        </table>
        <div class="d-flex justify-content-end">
          <h5>Total: <span class="price text-success">89$</span></h5>
        </div>
      </div>
      <div class="modal-footer border-top-0 d-flex justify-content-between">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-success">Checkout</button>
      </div>
    </div>
  </div>
</div>



<!-- Section-->
{% if item %}
{% for i in item %}
<section class="py-5">
  <section class="container px-4 px-lg-5 mt-5">
    <div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center">
      <div class="col mb-5">
        <div class="card h-100">
          <!-- Product image-->
          <img class="card-img-top" src="{{i.data.image}}" alt="..." />
          <!-- Product details-->
          <div class="card-body p-4">
            <div class="text-center">
              <!-- Product name-->
              <h5 class="fw-bolder mb-2">{{i.data.name}}</h5>
              <!-- Product price-->
              <h6 style="text-align:left"><b>Price:</b> {{i.data.price}}</h6>
              <h6 style="text-align:left"><b>Type:</b> {{i.data.item_type}}</h6>
              <h6 style="text-align:left"><b>Description:</b> {{i.data.description}}</h6>
            </div>
          </div>
          <!-- Product actions-->
          <div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
            <div class="text-center"><a class="btn btn-outline-dark mt-auto" href="#" style="background-color: #e920a3"
              id="{{d.id}}" onclick="onclick=OrderItem(this.id)">Add to Cart</a></div>
          </div>
        </div>
      </div>
    </div>
  </section>
</section>
{% endfor %}
{% endif %}

1 Answers

There is an issue with your serializer.

class OrderItemSerializer(serializers.ModelSerializer):
    item = ItemSerializer()
    class Meta:
        model= OrderItem
        fields= "__all__"

As you are using Item as a foreign key in OrderItem table. You should include its serializer too. It would work, I am sure.

Related