django - 如何在本地环境中使用 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”目录直接移动到媒体目录,但没有任何改变。我不知道我做错了什么,有人可以帮助我吗?
提前致谢 !
解决方案
推荐阅读
- flutter - Flutter 冻结数据与模型数据冲突
- ruby-on-rails - Rails 水平分片在测试环境中未连接
- delphi - Delphi Spinedit:获取上一个值
- excel - 恢复 VBA 窗口的顺序
- php - 在 laravel 中创建记录时出错 - mongo Application
- ios - IOS 大标题 - 在启动新活动时捕捉
- php - 在前端将值显示为不同的值
- python - 想了解Python中某些代码行的含义
- regex - fail2ban-regex 与 alert_json 格式的 snort 日志文件不匹配
- javascript - 我正在使用 javascript 创建一个反应式杂货列表,当我单击它时我想更改列表项的颜色