Reputation: 562
I stored a list of products in my django models with multiple images attached to each product as a foreignkey. I am trying to retrieve all the products and their respective images in my django views so that I can print them on the screen. However no matter what I do I keep getting the local variable 'product' reference before assignment error.
Models.py:
class product(models.Model):
title = models.CharField('', max_length=100, db_index=True)
price = models.CharField('', max_length=100, db_index=True)
description = models.CharField('', max_length=100, db_index=True)
class productimage(models.Model):
product = models.ForeignKey(product, on_delete=models.CASCADE)
product_images = models.FileField(blank=True)
views.py:
from django.shortcuts import render
from selling.models import product
from selling.models import productimage
from django.shortcuts import redirect
from django.template import loader
template = loader.get_template("selling/shop.html")
if product.objects.exists():
products = product.objects.all()
for product in products:
productimages = product.productimage_set.all()
for productimage in productimages:
imageurl = productimage.product_image.url
context = {
"products" : products,
"productimages" : productsimages,
}
Upvotes: 1
Views: 289
Reputation: 550
You could import product with a different name (or) change the variable name.
like
from selling.models import product as product_model
So in rest of the code you can use product_model
. That should clear all confusion and hence you should not have any issues.
Upvotes: 2
Reputation: 51988
I think you forgot to import product in view. So update your code like this:
from .models import product # use camel case when writing class name
Also you implementation is bit complicated in views(looping over product and product images). You can move most of them to template like this:
template = loader.get_template("selling/shop.html")
products = product.objects.all()
if products.exists():
context = {
"products" : products,
}
Template:
{% for product in products %}
{% for product_image in product.productimage_set.all %}
<img src="{{product_image.product_image.url}}">
{% enfor %}
{% endfor %}
Upvotes: 2