Search code examples
djangomodels

Django Blog Post Image


Added a featured image class which adds the ability to set a featured image for a blog post.

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 will upload to a directory like images/2012/12/19/image.png

I've updated admin.py and I can successfully upload and save a specific image to a blog post but I'm falling short on the knowledge to retrieve it. how can I finish get_image so I can get back the path to my image and then what do I use to display it? I'm thinking it would be something like...

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

I'm terribly new to Django and feel like I'm making major progress but I'm still slipping on some details.


Solution

  • try this

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

    Also your if condition for PostFeaturedImage in template should be {% if post.postfeaturedimage %} instead of {% if postfeaturedimage %}