I've looked through other answers to similar questions but I can't seem to get it to work. here is my model structure:
models.py
class Seller(models.Model):
seller_full_name = models.CharField(max_length=50)
seller_listing_name = models.CharField(max_length=50) <-- I want to display this in template
email = models.EmailField(max_length=50)
date_added = models.DateField(auto_now_add=True)
def __str__(self):
return self.seller_listing_name
# Create your models here.
class Product(models.Model):
...
seller = models.ForeignKey(Seller, on_delete=models.CASCADE, null=True, blank=True)
...
def __str__(self):
return self.product_name
In my view I get a query set of products
views.py
def store(request):
products = Product.objects.values().order_by('?') # shuffle order
args = {'products': products}
return render(request, 'store/products-page.html', args)
In the template I iterate through products and build cards that display item details. I want to also display the listing name of the seller for each product on each card. I cannot seem to get the foreign key statement correct in the view because it renders empty where the sellers name should be.
products-page.html
{% for product in products %}
<div class="col-lg-3 col-md-6 mb-4">
...
<p>
// {{ product.seller.seller_listing_name }} // <-- display sellers name here
</p>
<h4 class="card-title">
<a href="#">{{ product.product_name }}</a>
</h4>
<p>#{{ product.product_id }}</p>
<p>{{ product.description }}</p>
<h5>${{ product.price | floatformat:2 }}</h5>
...
</div>
{% endfor %}
I've been messing with this for awhile and I can't seem to get it so any help would be awesome!
EDIT Some links I've looked at:
Django: How to get data connected by ForeignKey via Template?
Django foreign key relation in template
How to access foreign key table's data in Django templates?
SOLUTION Thanks to the comments below I didn't realize that I was converting the products to a dictionary using .order_by('?') - This was resulting in a data structure that didn't keep my relationships so I wasn't able to access my FK.
views.py
def store(request):
products = Product.objects.order_by('?') # REMOVE .values()
args = {'products': products}
return render(request, 'store/products-page.html', args)
products-page.html
{% for product in products %}
<div class="col-lg-3 col-md-6 mb-4">
...
<p>
// {{ product.seller.seller_listing_name }} // <-- display sellers name here
</p>
<h4 class="card-title">
<a href="#">{{ product.product_name }}</a>
</h4>
<p>#{{ product.product_id }}</p>
<p>{{ product.description }}</p>
<h5>${{ product.price | floatformat:2 }}</h5>
...
</div>
{% endfor %}