2012-12-19 55 views
1

添加了一个精选图片类,它增加了为博客文章设置精选图片的功能。Django博客文章图片

class PostFeaturedImage(models.Model): 
    last_modified = models.DateTimeField(auto_now_add=True,editable=False) 
    created = models.DateTimeField(auto_now_add=True,editable=False) 
    title = models.CharField(max_length=20) 
    image = models.ImageField(upload_to='images/%Y/%m/%d') 
    post = models.ForeignKey(Post) 

    def get_image(self, field_attname): 
     """Get upload_to path specific to this photo.""" 
     return 'photos/%Y/%m/%d' % (""" need this to make it work """) 

图像将上传到一个目录像images/2012/12/19/image.png

我已经更新admin.py,我可以成功地上传和特定的图像保存到博客文章,但我的知识短暂下跌至检索它。我怎样才能完成get_image这样我就可以找回我的图像的路径,然后我用什么来显示它?我想这会是这样的......

{% if posts %} 
    {% for post in posts %} 
     {% if postfeaturedimage %} 
     <img src="{{post.postfeaturedimage.get_image}}" alt="{{post.postfeaturedimage.title}}"> 
     {% endif %} 
    {% endfor %} 
{% endfor %} 

我非常新Django和感觉我取得重大进展,但我仍然对一些细节打滑。

+0

该日期假设是从创建日期开始的? –

+0

是的。我是 试图让他们存档很像WordPress如何做。 – frankV

回答

2

试试这个

def get_image(self): 
    """Get upload_to path specific to this photo.""" 
    return self.image.url 

而且你if条件模板PostFeaturedImage应该是{% if postfeaturedimage %}{% if post.postfeaturedimage %}代替

+1

实际上,您不需要为此编写自定义模型方法。你可以直接在模板中调用'{{post.postfeaturedimage.url}}'。 – username

+1

我根据提问者的要求给出了答案。显然'post.postfeaturedimage.image.url'是一个较短的版本。 –

+1

也有时候图像方法很方便。例如如果存在,则返回图片网址,否则发送默认图片网址。 –

2

的get_image功能是不必要的。您可以从模板中获取图片网址,如下所示:

{{ post.postfeaturedimage.image.url }}