gpt4 book ai didi

python - Django : how to display images from database in template?

转载 作者:行者123 更新时间:2023-12-05 06:19:10 25 4
gpt4 key购买 nike

您好,我不知道为什么,但我无法显示数据库中的图像。我认为这是因为我在模板中的路径。

我的模型:

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)

我的观点:

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

我的网址:

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

设置:

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

我的模板:

{% 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 %}

并且: my tree view

以及我在模板上看到的内容 my image

最佳答案

urlpatterns 之后将其添加到您的 urls.py

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)

关于python - Django : how to display images from database in template?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60926603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com