Search code examples
pythondjangoimagefielddjango-1.10media-url

Unable to display ImageField within Django template


I hope you can help me withmy Django project. I am able to upload an images under a media_cdn folder, inside a folder based on the name of the slug. The problem occurs when I try to display the image inside my post list and post.

Can you please have a look at my code and offer a solution. I spent hours trying to get it to work. Please help.

settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn/')

models.py

def upload_location(instance, filename):
    return "%s/%s" %(instance.slug, filename)

class Post(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique=True)
    image = models.ImageField(upload_to=upload_location,
            null=True, 
            blank=True,
            width_field="width_field", 
            height_field="height_field")
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    body = models.TextField()
    date = models.DateTimeField()
    updated = models.DateTimeField(auto_now=True)

postlist.html

{% block content %}
    {% for post in posts %}
        <div class="container w3-card-4">
        {% if post.image %}
            <img src="{{ post.instance.image.url }}">
        {% endif %}
...

post.html

{% block content %}
<div class="row">
    <div class="container w3-card-4">
        {% if instance.image %}
        <img src= "{{ instance.image.url }}" class="img-responsive">
        {% endif %}
...

url.py

from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('personal.urls')),
    url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I don't know what else to try to call that image from the folder. Any advice would be greatly appreciated. Thank you!


Solution

  • Use post.image.url instead of post.instance.image.url. Check the documentation.

    ImageField inherits all the attributes of the FileField which includes url.