Geo
Geo

Reputation: 21

For loop in Django doesnt show up the result from database

i have a problem with for loop. First i have this views.py:

from django.shortcuts import render
from .models import *

def store(request):
    products = Product.objects.all()
    context = {'products':products}
    return render(request, 'store/store.html')

As you see from the .models i am importing everything (*), but in particular i am interested in class Product (code from models.py):

class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    price = models.FloatField()
    digital = models.BooleanField(default=False, null=True, blank=False)

    def __str__(self):
        return self.name

Then in Django admin http://127.0.0.1:8000/admin i have created several products: enter image description here

So i have the model, products in database and view. Finally in my template store.html i have for loop:

{% extends 'store/main.html' %}
{% load static %}
{% block content %}
    <div class="row">
       {% for product in products %}
        <div class="col-lg-4">
            <img src="{% static 'img/placeholder.png' %}" alt="" class="thumbnail">
            <div class="box-element product">
                <h6><strong>{{product.name}}</strong></h6>
                <button  class="btn btn-outline-secondary add-btn">Add to Cart</button>
                <a class="btn btn-outline-success" href="#">View</a>
                <h4 style="display: inline-block; float: right"><strong>${{product.price|floatformat:2}}</strong></h4>
            </div>
        </div>
        {% endfor %}
    </div>
{% endblock content %}

But it doesnt show the products from the database: enter image description here

If i delete in store.html a for loop: {% for product in products %} and {% endfor %} Then the plain html displays. enter image description here

Any clue why the for loop doesnt work please? I have done all the django stuff for database migration (makemigrations, migrate) and i see in folder "migrations" that the migrations was successfull.

Thank you

Upvotes: 0

Views: 114

Answers (2)

Arjun Shahi
Arjun Shahi

Reputation: 7330

You are not passing the context to your template from your view.

def store(request):
    products = Product.objects.all()
    context = {'products':products}
    return render(request, 'store/store.html', context)

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You did not pass the context to the render(…) function [Django-doc]:

def store(request):
    products = Product.objects.all()
    context = {'products':products}
    #                            pass the context ↓
    return render(request, 'store/store.html', context)

Upvotes: 2

Related Questions