显示通过 Django FileField() 上传的图像

问题描述 投票:0回答:1

我的网站中有一个用于辅导项目的 Django 模型,我希望能够上传每个项目的缩略图。我使用 FileField() 并将“upload_to=”设置为静态文件夹。我正在尝试使用 django 模板在网站中显示图像,我在标签中配置了“scr”属性,但是当 HTML 尝试获取图像时,我在 GET 响应上收到 404:

[01/Jan/2024 21:13:00] "GET /fit/static/fit/coaching/program_imgs/article_img.jpg HTTP/1.1" 404 3818

我只是希望能够在网站中显示上传到数据库的图像。 当我访问上传图像的文件夹时,图像就在那里,就像它应该的那样,我不知道为什么我不能在 HTML 中显示它。

重要提示:我直接通过 django 管理站点为文章创建数据库对象。

这是我的模型.py:

class coaching_programs(models.Model):
    coach = models.ForeignKey(User,on_delete=models.CASCADE, related_name='coach')
    title = models.CharField(max_length=35, unique=True)
    description = models.CharField(max_length=120)
    price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
    text = models.FileField(upload_to='fit/static/fit/coaching/program_text/',null=True,blank=True)
    # i will put md files in this filefield() above.
    img = models.FileField(upload_to='static/fit/coaching/program_imgs/',null=True,blank=True)

我的 HTML/ django 模板:

    {%for post in posts%}
        <div class="post">
            {{post.img}}
            <img src="../../../{{post.img}}" alt="">
            <p>{{post.title}}</p>
            <p>{{post.price}}</p>
            <p>{{post.description}}</p>
        </div>
    {%endfor%}

views.py:

def coaching(request):
    return render(request,"fit/coaching.html",{
        'posts':coaching_programs.objects.all(),
    })

如果其中有任何英语错误,我很抱歉,我是巴西人,并且是使用 Django 的初学者,所以非常感谢任何反馈!

python html django django-models django-templates
1个回答
0
投票

首先,当您想要将媒体上传到服务器时,您必须配置服务器以告诉它保存文件的位置

在settings.py中添加

MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media'

在 url.py 中添加

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

然后在 models.py 中

class coaching_programs(models.Model):
      ...
     text = models.FileField(upload_to='fit/coaching/program_text/',null=True,blank=True)
     img = models.FileField(upload_to='fit/coaching/program_imgs/',null=True,blank=True)
     # the downloaded files will have as root the MEDIA_ROOT configured in settings.py

终于在 django 模板中

{%for post in posts%}
   ...
   <img src="{{post.img.url}}" alt="">
   ...
{%endfor%}
© www.soinside.com 2019 - 2024. All rights reserved.