Midlandgeeks - Cloud Solutions for SME’s    

Wrangling images when using Django as Blog Engine

Wrangling images when using Django as Blog Engine

Using Django to host your Blog Engine can find you wrestling with rendering images particularly if you are using the django admin application as part of your deployment. Notoriously, when you think your images associated with the post are all sitting correctly - you find that images aren’t displayed with 404 Not Found messages encountered.

Take heed of the following four touch-points if images aren’t being displayed:

1. Everything is relative to the root apex of your project deployment. Your blog app deployment will sit under your project path for example /path/to/myproject/blog

2. Have a clear understanding of your static and media files storage location. Keep in mind these files are mostly auxiliary to django and are mostly dictated by your web server configuration. Ensure these are declared in your setting.py like so

STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/‘

3. Where possible use the models.ImageField to declare your image object. class BlogPost(models.Model): title = models.CharField(_('title'), max_length=255) slug = AutoSlugField(_('slug'), populate_from='title', unique=True, null=False) image = models.ImageField(_('image'), blank=True, null=True, upload_to=‘’ If you declare a folder with upload_to=‘media’ expect it to upload to blog/media

4. For the above, the html rendering should look like -

  <img src="media/{{ blog_post.image }}" alt="{{ blog_post.title }}" class="img-fluid { width="640" height="360"; } mb-3”>

5. Declare your media setting in the blog apps url.py

path('', BlogPostListView.as_view(), name='list'), path('', BlogPostDetailView.as_view(), name='detail'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Of course, it all depends on your blog application but this should give you things to think about if your images aren’t rendering.

Caveats

This blog is transiting from a tech blog to a Travel and Arts blog. The simple reason is that I have now retired from the tech field and mostly try to spend my time in the travel and arts space. It is intended to emphasize a cultural slant through art on my travel tours by promoting various artists and their work which is or has been popular in Trinidad and Tobago and throughout the Caribbean...

Know more!