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.
.This blog is mostly about helping small and medium sized businesses use technology. Size necessarily dictates different priorities but the ability to apply the tools available to differentiate your online presence should not be a constraint to growing your business. Helping you bring your ideas to fruition is what we’re about. Perhaps developing ways which allow you to better connect with your customers by implementing a new service platform or simply a rejuvenation of your website...
Know more!