模板中的Django外键对象图像

时间:2012-10-31 05:15:19

标签: python django web

好的,我知道有一千人问过这个问题,但我已经看过这个网站没有成功(也是谷歌)这里是我的models.py

VENUE_IMAGE_PATH = os.path.join('images', 'venue_profiles/%Y/%m/%d')

 class Venue(models.Model):

    .....................
   name = models.CharField(max_length=100)
   address = models.CharField(max_length=100)
   city = models.CharField(max_length=100)
   ...........................

class VenueImage(models.Model):
  venue = models.ForeignKey(Venue, related_name="venue")
  image = models.ImageField(upload_to=VENUE_IMAGE_PATH, max_length=255)

这是我的views.py

def list(request):
  venues = Venue.objects.all()
  images=VenueImage.objects.all()

 return render_to_response('venues/list.html', {'venues':venues,'images':images}, 
  context_instance = RequestContext(request)) 

这是我的模板

{% for v in venues %}

<a href='#'>{{v.name}}</a>
<a href="{% url edit v.id %}" style="position:relative;left:10px;">edit</a>

{% if images %}
<img class='venue_image' src='images/venue_profiles/2012/10/25/{{images.url}}' 
    alt=''>
    {% endif %}
    {% endfor %}

现在我尝试了{{images.images.url}}{{images.url}}{{MEDIA_URL}}images/venue_profiles/%Y/%m/%d/{{image.url}}。 我也试过了{%for i in images %} {{i.url}} {% endfor %}。 我也试过没有'images/venue_profiles/2012/10/25'前缀,似乎没有任何效果。 有人可以帮我看看我做错了什么。

1 个答案:

答案 0 :(得分:1)

# In models.py

class Venue(models.Model):
    ....
    name = models.CharField(max_length=100)
    ....
    images = models.ForeignKey(VenueImage)

class VenueImage(models.Model):
    image = models.ImageField(upload_to=VENUE_IMAGE_PATH)

# In views.py

def list(request):
    venues = Venue.objects.all()
    return render(request,
                  'venues/list.html',
                  {'venues': venues'})

# In template

{% for venue in venues %}
<a href '#'>{{ venue.name }}</a>
...
{% for image in venue.images %}
<img class='venue_image' src=''{{ image.url }}' alt=''>
{% endfor %}
{% endfor %}