【问题标题】:Struggling to display images using django努力使用 django 显示图像
【发布时间】:2022-01-03 02:38:52
【问题描述】:

我正在使用 django 框架创建一个博客网站,因此我很难在动态页面上显示图像。这是我的代码:

models.py:

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_posts')
    updated_on = models.DateTimeField(auto_now=True)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now=True)
    status = models.IntegerField(choices=Status, default=0)
    cover_image = models.ImageField()
    captioned_image = models.ImageField()
    caption = models.CharField(max_length=300)

    class Meta:
        ordering = ['-created_on']
    
    def __str__(self):
        return self.title

views.py:

def post(request, slug):
    post = Post.objects.get(slug = slug)
    context = {'post': post}
    return render(request, template_name='blogger/pages.html', context=context)

在我的 html 中:

<img class="img-fluid" src="{{post.cover_image.url}}" />

我不确定我在这里做错了什么,因为文本在我的代码中动态正确显示,只是无法处理图像。

【问题讨论】:

    标签: python html django dynamic


    【解决方案1】:

    有几件事可能会出错。你使用的是 Django 自带的开发服务器还是生产服务器?默认情况下,Django 在开发过程中不提供媒体文件。您需要通过将其放入您的url.py

    来启用它
    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        ...]
    if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,
                              document_root=settings.MEDIA_ROOT)
    

    另外,请确保您已配置 MEDIA_ROOT 和 MEDIA_URL。最基本的方法是将其添加到您的 settings.py

    # Base url to serve media files
    MEDIA_URL = '/media/'
    
    # Path where media is stored
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
    

    如果这些都不能解决问题,我们可能会帮助我们查看运行服务器的终端的输出和/或开发人员工具中的网络选项卡的外观(确保只选择图像以便更容易阅读)

    【讨论】:

    • 是的,这解决了它!谢谢!
    【解决方案2】:

    为您的图片字段提供一个“upload_to”,以便您的图片上传到那里。

    cover_image = models.ImageField(upload_to="Folder")
    

    【讨论】:

    • 仍然没有,实际上当我通过管理站点上传文件时,它已成功将文件上传到文件夹,但无法在 html 中呈现
    • 尝试安装枕头模块。 pip install pillow
    • 是的,已经安装了
    • 尝试在浏览器中通过View page source查看cover_image的src。
    猜你喜欢
    • 2022-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2022-08-14
    • 2023-04-01
    • 1970-01-01
    • 2016-01-25
    相关资源
    最近更新 更多