Home > front end >  Struggling to display images using django
Struggling to display images using django

Time:01-03

I am creating a blogging website using django framework and so I am struggling to display images on dynamic pages. Here is my code:

models.py:

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_posts')
    updated_on = models.DateTimeField(auto_now=True)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now=True)
    status = models.IntegerField(choices=Status, default=0)
    cover_image = models.ImageField()
    captioned_image = models.ImageField()
    caption = models.CharField(max_length=300)

    class Meta:
        ordering = ['-created_on']
    
    def __str__(self):
        return self.title

views.py:

def post(request, slug):
    post = Post.objects.get(slug = slug)
    context = {'post': post}
    return render(request, template_name='blogger/pages.html', context=context)

within my html:

<img  src="{{post.cover_image.url}}" />

I am unsure what I am doing incorrect here as text is correctly displaying in my code dynamically, just unable to work with images.

CodePudding user response:

There's a couple things that might be going wrong. Are you using the development server that comes packaged with Django or a production server? Django doesn't serve media files during development by default. You need to enable it by putting this in your url.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    ...]
if settings.DEBUG:
    urlpatterns  = static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

Also, make sure you have MEDIA_ROOT AND MEDIA_URL configured. The most basic way of doing this is adding this to your settings.py

# Base url to serve media files
MEDIA_URL = '/media/'

# Path where media is stored
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

If neither of these fix the issue, it might be helpful for us to see the output of your terminal where the server is running and/or what the network tab in your developer tools looks like (make sure to just select images so it's easier to read)

CodePudding user response:

Provide an "upload_to" for your image field so that your images upload there.

cover_image = models.ImageField(upload_to="Folder")
  • Related