how to display a foreign key image of an object in an object_list view/template?

362 views
Skip to first unread message

Bledi

unread,
Jul 10, 2017, 5:14:10 PM7/10/17
to Django users
I am trying to build a website where you can sell stuff. I want the user to be able to upload multiple images per product/post. I think I have figured that part out. But I am struggling to display one image per product. Here are the details:


models.py (I have left out some basic methods)

class Product(models.Model):
    title=models.CharField(max_length=200)
    description=models.TextField(max_length=1000)
    price = models.DecimalField(max_digits=12, decimal_places=2)
    user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL)
 
class ProductImages(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    product_fk = models.ForeignKey(Product, on_delete=None, to_field="id")
    image = models.ImageField(upload_to=image_location)

####################################
views.py

*function for product_detail_view

def products_detail(request, pk):
    productt = get_object_or_404(Product, id=pk)
    images = get_list_or_404(ProductImages, product_fk=pk)
    context = {'images': images, 'productt':productt}
    return render(request, 'index5.html', context)
##################################
urls.py

url(r'^list/(?P<pk>\d+)$', views.products_detail, name='list_products_detail'),
##################################

** I need a function to list all products and one image per product. Same as when you search for a product in any website where there is an image per product.
I have tried to solve this on my own, but I was not able.


I have tried using generic.ListView but failed.

ecas

unread,
Jul 11, 2017, 5:29:15 AM7/11/17
to Django users

You can query for the images, and keep the first one for the template rendering.

products = Product.objects.all()
for product in products:
    products.image = product.productimages_set.first()




Bledi

unread,
Jul 11, 2017, 10:20:00 AM7/11/17
to Django users
Thanks, but I am getting this error:

'Product' object has no attribute 'productimages_set'

ecas

unread,
Jul 11, 2017, 11:13:54 AM7/11/17
to Django users
There was a typo:

products = Product.objects.all()
for product in products:
    product.image = product.productimages_set.first()


Other than that, it should work. You could try this in the django shell, just to verify the reverse name of the relationship.

from your_app.models import *
product=Product.objects.first()
product.productimages_set.first()

And debug from there.

El dimarts, 11 juliol de 2017 16:20:00 UTC+2, Bledi va escriure:
Reply all
Reply to author
Forward
0 new messages