首页 > 解决方案 > 如何在本地环境中使用 Django 提供媒体文件?

问题描述

尝试在模板中显示来自我的媒体文件的图片(例如来自用户的个人资料图片)时出现问题。我已经看过很多主题,每次的答案都是urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)在 urls.py 文件中添加一行。但我已经有了它,它仍然无法正常工作。以下是我文件的相关部分:

网址.py

from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('actualites.urls')),
    path('inscription/', include('inscription.urls')),
]

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

设置.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

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

MEDIA_URL = '/media/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

视图.py

def home(request):
    return render(request, 'actualites/home.html', {'last_meals': Plat.objects.all()})

模型.py

class Plat(models.Model):
    titre = models.CharField(max_length = 100)
    date = models.DateField(default=timezone.now, verbose_name="Date de préparation")
    photo = models.ImageField(upload_to = "photos_plat/", blank = True)

    class Meta:
        verbose_name = "Plat"
        ordering = ['date']

    def __str__(self):
        return self.titre

可以看到图片记录在photos_plat目录下,该目录是media目录的子目录。

模板:

{% extends "base.html" %}
{% block content %}
    <h2>Bienvenue !</h2>
    <p>
       Voici la liste des plats disponibles :
    </p>

    {% for meal in last_meals %}
      <div class="meal">
        <h3>{{ meal.title }}</h3>
        <img src="{{ meal.photo.url }}" height=512 width=512/>
        <p>{{ meal.description|truncatewords_html:10 }}</p>
        <p><a href="{% url 'display' meal.id %}">Afficher le plat</a></p>
      </div>
    {% empty %}
      <p>Aucun plat disponible.</p>
    {% endfor %}
{% endblock %}

当我进入主页时,出现以下错误:ValueError at / The 'photo' attribute has no file associated with it. 我尝试将图片从“photos_plat”目录直接移动到媒体目录,但没有任何改变。我不知道我做错了什么,有人可以帮助我吗?

提前致谢 !

标签: djangodjango-templatesdjango-staticfilesdjango-media

解决方案


推荐阅读