Julien Corbin Julien Corbin - 3 years ago 75
Python Question

Display image in template with Django

I am trying to display images into articles in my blog project built with Django. Here is the related code:


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

urls.py (project):

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


class Article(models.Model):
title = models.CharField(max_length=150)
slug = models.SlugField(max_length=150)
author = models.CharField(max_length=80)
text = models.TextField(null=True)
date = models.DateTimeField(auto_now_add=True, auto_now=False,
verbose_name="Date de parution")
image1 = models.ImageField()
image2 = models.ImageField()
image3 = models.ImageField()

def __str__(self):
return self.titre


def article(request, id, slug):
article = get_object_or_404(Article, id=id, slug=slug)
return render(request, 'blog/post.html', {'article': article})


<img src="{{ article.image1.url }}"/>
<img src="{{ article.image2.url }}"/>
<img src="{{ article.image3.url }}"/>

However, it does not work. Images do not appear. Any suggestions ?

Answer Source

There shouldn't be any forward slashes before or after media, it should simply be .join(BASE_DIR, 'media'). also you don't need to add upload_to('media') because the root is media. You are not advised to add images in media root, you should create an img folder inside media folder, and then add upload_to('img/') in your imagefield.

Regarding inserting image preview inside a textbox/textfield, yes it is possible, but it should be a separate question, although I think there are many identical questions on it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download