媒体文件未显示

时间:2016-04-06 14:59:21

标签: django python-3.x heroku

我一直在学习django,从我读过的内容来看,MEDIA和STATIC应该分开,所以我有

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
    STATIC_URL = '/static/'

    MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media_cdn')
    MEDIA_URL = '/media/'

    # Extra places for collectstatic to find static files.
    STATICFILES_DIRS = (
        os.path.join(PROJECT_ROOT, 'static'),
        os.path.join(PROJECT_ROOT, 'media'),
    )

我有能力从我的网站创建帖子,当我在本地开发时,网址就是这个

/media/None/earthquake.png

来自这个

{{post.image.url}}

我就像这样使用它

<img src='{{post.image.url}}>

显示图像

我读过的文档我并没有使用静态来获取图片。

这是我的帖子模型

def upload_location(instance, filename):
    return "{}/{}".format(instance.id, filename)


class Post(models.Model):

    STATUS_CHOICES = (
       ('draft', 'Draft'),
       ('published', 'Published'),
    )
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250,
                            unique_for_date='publish')
    image = models.ImageField(upload_to=upload_location,
                              null=True,
                              blank=True,
                              height_field='height_field',
                              width_field='width_field')
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    author = models.ForeignKey(User,
                               related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,
                              choices=STATUS_CHOICES,
                              default='draft')
    video = models.BooleanField(default=False)
    video_path = models.CharField(max_length=320,
                                  null=True,
                                  blank=True,)

我正在关注一个教程,我认为upload_location函数可能是问题,尽管我可能错了。如何让我的图像在制作中显示?我已经安装了whitenoise,但是在文档中它表示像这样提供我的图像

{% load static %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!" />

所以我试过这个

 <img src="{% static 'None/car.jpg' %}" alt="Hi!"  width="100" height="100"/>

这是我的文件结构

enter image description here

如何在生产中显示我的图像

此示例未显示如何动态显示图像。我的每个帖子都有自己的照片。这不起作用

<img src="{% static '{{post.image.url'%}" alt="Hi!"  width="100" height="100"/>

1 个答案:

答案 0 :(得分:1)

在Heroku上以这种方式存储和提供用户上传的媒体是不可能的。您无需在磁盘上本地存储媒体,而是需要将其存储在Amazon S3等支持服务上。查看Django Storages包,它为许多不同的服务提供存储后端。

相关问题