如何通过Django中的模板通过外键连接图像 [英] How to get image connected by Foreign Key via Template in django

查看:111
本文介绍了如何通过Django中的模板通过外键连接图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从模板中的图像模型中获取图像.

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

我已阅读链接

我尝试过:

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

但没有成功..

推荐答案

您的代码有太多错误,我建议您首先执行Django教程.

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 %}

这篇关于如何通过Django中的模板通过外键连接图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆