需要帮助才能显示模型中的图像

时间:2017-01-21 08:13:53

标签: python django web django-models django-templates

我有一个名为' Page'我想为每个Page对象存储许多图像。 所以我创建了一个名为' Image'的独立模型。作为“Page”的F.K'模型。

在我的模板中,我将所有Page对象显示为一个列表(使用bootstrap),但对于每个对象,我还想显示为每个对象保存的许多图像,我无法弄清楚循环部分。我在下面给出了相关代码:

Models.py



class Page(models.Model):
    name=models.CharField(max_length=10,unique=True)
    views = models.IntegerField(default=0)
    slug = models.SlugField( )
    #description field
    des=models.TextField(max_length=500,blank=False)
    def save(self, *args, **kwargs):
            # Uncomment if you don't want the slug to change every time the name changes
            #if self.id is None:
                    #self.slug = slugify(self.name)
            self.slug = slugify(self.name)
            super(Page, self).save(*args, **kwargs)
    def __str__(self):
        return self.name

def desti (instance,filename):
    return "%s/%s/%s"%(instance.page,instance.user,filename)

class image(models.Model):
    user=models.ForeignKey(User)
    page=models.ForeignKey(Page)
    images=models.ImageField(upload_to=desti, null=False ,blank=False)




的index.html



{% for obj in page_list %}
        <div class="card" style="width: 20rem;">)
            {% for obj2 in obj.images %}
                <img class="card-img-top" src="{{ }}" alt="IMAGE GOES HERE">
           <!-- want to display the images here as horizontal -->
          {% endfor %}
            <h1>this page has {{ obj.images }} images </h1>
                  <div class="card-block">
                    <h4 class="card-title">{{ obj.name }}</h4>
                    <p class="card-text">{{ obj.des }}</p>
                    <a href="#" class="btn btn-primary">ViewDetails</a>
                  </div>
        </div>
        <hr>
    {% endfor %}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

可能很简单:

class image(models.Model):
    user=models.ForeignKey(User)
    page=models.ForeignKey(Page, related_name='images')
    pic =models.ImageField(upload_to=desti, null=False ,blank=False)

在模板中:

{% for page in page_list %}
        <div class="card" style="width: 20rem;">)
        {% for image_obj in page.images.all %}
            <img class="card-img-top" src="{{ image_obj.pic.url}}" alt="IMAGE GOES HERE">
       <!-- want to display the images here as horizontal -->
      {% endfor %}
<h1>this page has {{ page.images }} images </h1>
                  <div class="card-block">
                    <h4 class="card-title">{{ page.name }}</h4>
                    <p class="card-text">{{ page.des }}</p>
                    <a href="#" class="btn btn-primary">ViewDetails</a>
                  </div>
        </div>
        <hr>
    {% endfor %}