Django博客发布图片

时间:2012-12-19 20:27:52

标签: django models

添加了一个精选图片类,可添加为博客帖子设置精选图片的功能。

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非常陌生,觉得我正在取得重大进展,但我仍然在滑倒一些细节。

2 个答案:

答案 0 :(得分:2)

试试这个

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

此外,模板中if的{​​{1}}条件应为PostFeaturedImage而不是{% if post.postfeaturedimage %}

答案 1 :(得分:2)

不需要get_image函数。您可以从模板中获取图片网址:

{{ post.postfeaturedimage.image.url }}