nesu
nesu

Reputation: 35

Display Django Foreign key on webpage

I have three models.

class Supplier(models.Model):
name = models.CharField(max_length=200, null=True)


class Order(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)


class Product(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True, blank=True)
on_order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, blank=True)

I can display a table of all the products of a given order. However, I cannot seem to render the name of that supplier on the html page like <h4> Supplier: {{order.supplier}}</h4>

this is the view:

def PurchaseOrder(request, pk_order):
    orders = Order.objects.get(id=pk_order)
    products = Product.objects.filter(
    on_order_id=pk_order).prefetch_related('on_order')
    total_products = products.count()
    supplier = Product.objects.filter(on_order_id=pk_order).prefetch_related('on_order')

context = {
    'supplier': supplier,
    'products': products,
    'orders': orders,
    'total_products': total_products, }

return render(request, 'crmapp/purchase_order.html', context)

here is my template:

{% extends 'crmapp/base.html' %}
{% load static %}
{% block content %}

<div class='main-site>'>
<h4> Supplier: {order.supplier}}</h4> **<----Does not work**
<h5>Order Number: {{order.id}}</h5> **<----Does not work**
<h5>Created on: {{order.date_created | date:"d/m/Y"}}</h5> **<----Does not work**
<h6>Total Items on Order: {{total_products}}</h6>

      <input type="search" placeholder="Search any field..." class="form-control search-input" data-table="customers-list"/>
      <table class="table table js-sort-table mt32 customers-list" id='myTable'>
      <thead class="table" >
    <tr>
      <th class='header' onclick="sortTable(0)" scope="col">ID</th>
      <th class='header' onclick="sortTable(1)" scope="col">Description</th>
      <th class='header' onclick="sortTable(2)" scope="col">Cost</th>
      <th class='header' onclick="sortTable(3)" scope="col">Order Quantity</th>

    </tr>
  </thead>
  <tbody>
      <tr>
  {% for product in products %}
      <td> <a href="{% url 'productpage' product.id %}">{{product.id}}</a></td>
      <td><h6><strong>{{product.description}}</strong></h6></td>
      <td>£{{product.costprice |floatformat:2}}</td>
      <td>{{product.on_order_quantity |floatformat:0}}</td>


    </tr>
 </tbody>
 {% endfor %}

{% endblock %}

I've tried so hard... and didn't get very far. Please help...

Upvotes: 0

Views: 32

Answers (1)

OlegТ
OlegТ

Reputation: 181

in context you write "orders", but in template you ask for "order", which is not defined. Try

<h4> Supplier: {{orders.supplier}}</h4>

Upvotes: 1

Related Questions