Search code examples
djangoimagetemplatesmediablogs

Displaying image URL on Django Blog Home Page


I am not able to load my blog image on landing page. Please any one can solve this issue.

my HTML code inside for loop:

{% for item in object_list %}


<img class="rounded" src="{{item.main_image.url}}">

It gives error The 'main_image' attribute has no file associated with it.

I am able to load the images in detail page by simply doing this:

src="{{object.main_image.url}}">

My Model:

class Item(models.Model):
    title = models.CharField(max_length=100)
    description= RichTextField(blank=True, null=True)
    main_image= models.ImageField(null=True, blank=True,upload_to='images/')
    date = models.DateTimeField(auto_now_add=True)
    item_slug = models.CharField(max_length=200, default=1)
    item_category = models.ForeignKey(Categories, default=1, on_delete=SET_DEFAULT)

Solution

  • Because your image is optional, you need to check to see if the image exists before you try to access it, because while it doesn't exist, it doesn't have a URL.

    To do this, check before accessing it in your template;

    {% if item.main_image %}
        <img class="rounded" src="{{ item.main_image.url }}">
    {% else %}
        <p>No image</p>
    {% endif %}