Django : how to display images from database in template?

Viewed 897

Hi I don't know why but I can't display images from my database. I think it is because of my path in my template.

My model :

class Article(models.Model):
    titre = models.CharField(max_length=200)
    auteur = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date de publication')
    numero = models.CharField(max_length=200)
    categorie = models.CharField(max_length=200, default="culture")
    contenu = models.CharField(max_length=200000)
    image = models.ImageField(upload_to='image_publie', blank=True, null=True)

    def __str__(self):
        return self.titre

    def was_published_recently(self):
        return self.pub_date >= timezone.now() -datetime.timedelta(days=7)

My view :

def detail(request, article_id):
    article = get_object_or_404(Article, pk=article_id)
    return render(request, 'gazette/detail.html', {'article':article})

My url :

path('<int:article_id>/', views.detail, name='detail'),

Settings :

STATIC_URL = '/static/'
MEDIA_URL = '/images/'
MEDIA_ROOT = os_path.join(BASE_DIR, 'images/')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

My template :

{% extends "base.html" %}
{% load static %}

{% block content %}
<h1>{{ article.contenu }}</h1>
<ul>
 {% if article.image %}

    <img src="{{article.image.url}}" alt="{{article.titre}}" style="width: 200px; height: 200px;">

 {% endif %}
</ul>
{% endblock %}

And : my tree view

And what I see on my template my image

1 Answers

Add this into your urls.py after urlpatterns

from django.conf import settings

if settings.DEBUG:
    from django.conf.urls.static import static
    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
Related