How to get image connected by Foreign Key via Template in django

浪子不回头ぞ 提交于 2019-12-13 01:06:33

问题


i want to get the images form the image model in the template.

class Products(models.Model):
    category = models.ForeignKey(Category)
    name= models.CharField(max_length=120, unique=True)
    slug = models.SlugField(unique = True)
    price = models.IntegerField(default=100)


class Image(models.Model):
    property = models.ForeignKey(Products, related_name='images')
    image = models.ImageField(upload_to='static/images/home',blank=True,null=True)

views.py

def index(request):
  queryset = Products.objects.all()
  return render_to_response('site/index.html',
                            locals(),
                            context_instance=RequestContext(request))



{% for query in queryset %} 
   <img src='/ {{ query.????? }} ' alt="" width = 'auto' height='340'/>
{% endfor %}

i want to get the images which is connected to that product

i have readed that link

i have tried:

{% for query in queryset %} 
   <img src='/ {{ query.images_all.0.image }} ' alt="" width = 'auto' height='340'/>
{% endfor %}

but no success ..


回答1:


There is so much wrong with your code, I suggest that you do the Django Tutorial first.

https://docs.djangoproject.com/en/1.8/intro/tutorial01/

But if you wan't it working, here is how:

models.py

class Product(models.Model):
    category = models.ForeignKey(Category)
    name= models.CharField(max_length=120, unique=True)
    slug = models.SlugField(unique = True)
    price = models.IntegerField(default=100)

    def first_image(self):
        # code to determine which image to show. The First in this case.
        return self.images[0]

class ProductImage(models.Model):
    image = models.ImageField(upload_to='static/images/home',blank=True,null=True)
    product = models.ForeignKey(Product, related_name='images')

views.py

def index(request):
    queryset = Products.objects.all()
    return render_to_response('site/index.html', {'products': queryset})

index.html

{% for product in products %} 
     <img src="{{ product.first_image.src }}" alt="" width="auto" height="340"/>
{% endfor %}


来源:https://stackoverflow.com/questions/33432785/how-to-get-image-connected-by-foreign-key-via-template-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!