我正在尝试将上传的图像加载到模板中。图片已正确上传,网址也正确,但是我仍然收到404错误。错误是:-GET http://127.0.0.1:8000/media/complaints_image/motivational-inspirational-quotes-30.jpg 404(未找到)
该图像位于文件夹中:- inside the media folder image is present
模板
{% if complaint.media %}
<img src="{{ complaint.media.url }}" height="100px" width="100px" >
{% endif %}
settings.py
MEDIA_DIR = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
models.py
class Complaints(models.Model):
media = models.ImageField(upload_to='complaints_image',blank=True)
forms.py
class ComplaintForm(forms.ModelForm):
class Meta():
model = Complaint
fields = ('department','heading','text','media',)
答案 0 :(得分:0)
如果您将MEDIA_URL
定义为'/media/'
,则可以通过向entry-level urls.py
添加以下代码段来提供媒体文件:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
阅读Serving files uploaded by a user during development了解更多详细信息。
阅读this article,了解有关生产服务器的操作的详细信息。