While learning it, I faced with an issue, when I'm trying to show data from db, template doesn't see it. I tried to remove db and migrations and create new with new objects, but it didn't helped.
models file:
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
class Product(models.Model):
name= models.CharField(
max_length= 100,
verbose_name= 'Name'
)
description= models.TextField(max_length= 500)
photo= models.ImageField(upload_to= 'photos/%Y/%m/%d')
price= models.FloatField(validators= [MinValueValidator(2.0), MaxValueValidator(1000000.0)],)
amount= models.IntegerField()
last_updated= models.DateTimeField(auto_now= True)
is_published=models.BooleanField(default=False)
category= models.ForeignKey(
"Category",
verbose_name= 'Category',
default='Unselected',
on_delete=models.SET_DEFAULT
)
class Meta:
verbose_name = "Product"
verbose_name_plural = "Products"
def __str__(self):
return self.name
class Category(models.Model):
name=models.CharField(max_length=100)
class Meta:
verbose_name = 'Category'
verbose_name_plural = "Categories"
def __str__(self):
return self.name
views file:
from django.shortcuts import render
from .models import *
# Create your views here.
def index(request):
print(request)
product=Product.objects.all()
return render(request,'main.html',{product :'product'})
template file:
{% for item in product %}
<h1>{{item.name}}</h1>
{% if item.photo %}
<img src="{{item.photo.url}}" alt="Not found">
{% endif %}
<p>{{item.description}}</p>
<h2>{{item.price}}</h2>
{% endfor %}
I didn't show full html file,due to stackoverflow didn't let me to post it, because there is a lot of code, and no text
CodePudding user response:
change :
return render(request,'main.html',{product :'product'})
to :
return render(request,'main.html',{'product' : product})