2012-10-31 75 views
0

好吧,我知道一千人問這個,但我都找過這個網站沒有成功(也是谷歌)這是我的models.pyDjango的外鍵對象圖像

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) 

這是我的看法的.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
# 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 %}