我已经阅读了所有相关的线程并且已经用尽了我的研究,我所做的似乎没有任何效果。我将包括相关代码:
模型.py
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
posted = models.DateTimeField(db_index=True, auto_now_add=True)
body = models.TextField(blank=True)
category = models.ForeignKey('myapp.Category')
images = models.ForeignKey('myapp.Image')
def __unicode__(self):
return self.title
@permalink
def get_absolute_url(self):
return ('teensite.myapp.views.view_post', None, {'slug': self.slug})
class Image(models.Model):
def content_file_name(instance, filename):
return os.path.join(MEDIA_ROOT, filename)
title = models.CharField(max_length=60, blank=True, null=True)
number = models.IntegerField()
image = models.FileField(upload_to=content_file_name)
body = models.TextField(blank=True)
citation = models.URLField(blank=True)
created = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
"""Save image dimensions."""
super(Image, self).save(*args, **kwargs)
im = PImage.open(os.path.join(MEDIA_ROOT, self.image.name))
self.width, self.height = im.size
super(Image, self).save(*args, ** kwargs)
def __unicode__(self):
return self.image.name
def size(self):
"""Image size."""
return "%s x %s" % (self.width, self.height)
def get_absolute_url(self):
return ('http://www.teensdigest.com/media/'+self.image.name)
视图.py
def home(request):
return render(request, 'home.html', {'cats': Category.objects.all(),
'blogs' : reversed(Blog.objects.all()),
})
主页.html
{% for blog in blogs %}
{% with blog.images_set.all|first as pic %}
<div class="gal_grid_item" href="{{ blog.get_absolute_url }}">
<a class="gal_grid_image_wrapper" href="{{ blog.get_absolute_url }}">
<img class="gal_grid_image" src="{{ pic.get_absolute_url }}" />
</a>
<a class="gal_grid_info" href="{{ blog.get_absolute_url }}">
<p class="gal_title text-center">{{ blog.title }}</p>
</a>
</div>
{% endwith %}
{% endfor %}
我需要 home.html 模板来显示 blog.images 中的第一张图片。问题在于 {{ pic.get_absolute_url }} 模板的其余部分按预期呈现,但 {{ pic.get_absolute_url }} 没有返回值。我尝试过其他方法来访问 Image 模型中的其他值,但它们都不像 {{ blog.images.all.0.title }} 等
请帮忙,谢谢!