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的新手,觉得我正在取得重大进展,但我仍在浏览一些细节。

尝试此

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

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

get_image函数是不必要的。您可以从模板上达到图像URL:

{{ post.postfeaturedimage.image.url }}

最新更新