【问题标题】:Created website using Django, but the images are not showing when deployed to heroku but shows in localhost使用 Django 创建网站,但图像在部署到 heroku 时未显示,但在 localhost 中显示
【发布时间】:2020-04-20 07:52:07
【问题描述】:

图片来自管理员上传图片的表格:

这些是我存储静态文件和媒体的设置:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'portfolio/static/')

 ]

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

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

我创建的模型:

from django.db import models

# Create your models here.
class ProfileImage(models.Model):
    image = models.ImageField(upload_to='images/')

class Job(models.Model):
    image = models.ImageField(upload_to='images/')
    summary = models.CharField(max_length= 200)

class Project(models.Model):
    image = models.ImageField(upload_to='images/')
    summary = models.TextField()
    title = models.CharField(max_length=30)
    link = models.URLField(max_length=200, null=True, blank=True)

    def __str__(self):
        return(self.title)

class Social(models.Model):
    image = models.ImageField(upload_to='images/')
    title = models.CharField(max_length=30)
    link = models.URLField(max_length=200, null=True, blank=True)

    def __str__(self):
        return(self.title)

class Skills(models.Model):
    title = models.CharField(max_length=20)

    def __str__(self):
        return(self.title)

在我有的模板中:

 <img src="{{profile_pic.image.url}}" height="600px" width="500x" class="img-fluid img-thumbnail"
            alt="Responsive image">
          <br>

在我的观点中:

from django.shortcuts import render
from .models import Job, Skills, Project, Social, ProfileImage

# Create your views here.
def home(request):
    jobs = Job.objects.all()
    skills = Skills.objects.all()
    projects = Project.objects.all()
    socials = Social.objects.all()
    profile_pic = ProfileImage.objects.all().first()
    context = {'jobs':jobs, 'skills':skills, 'projects':projects, 'socials':socials, 'profile_pic':profile_pic}
    return render(request, 'jobs/home.html', context)

当我部署到 heroku 时,它显示:

【问题讨论】:

    标签: python django image heroku deployment


    【解决方案1】:

    您如何提供静态文件? Whitenoise 您可以使用它或其他服务(如 google cloud 或 aws)在生产环境中提供静态文件。

    以下是 Heroku 在其开发中心关于如何在生产中提供静态文件的内容。 Serve static files on heroku

    【讨论】:

    • 我是部署到 Heroku 的新手,但对白噪声了解不多。你能解释一下我如何使用白噪声吗?谢谢
    • 这样做其实很简单! Heroku 一步一步地介绍了如何在生产中在 Heroku 上配置白噪声,所以我会尝试遵循这个:devcenter.heroku.com/articles/django-assets 看看你是否能实现你的目标。
    • 实际上我正在从管理面板上传图像,当我单击管理面板内的图像时,“/app/media/images/flask.jpg”不存在。我搜索了答案,发现图像应该存储在 S3 服务器中。是否有不需要任何信用卡详细信息的 S3 替代方案?
    • 这也是我所知道的。您必须将它们保存在 s3 中,然后才能在生产中使用它们。你知道我还在学习试图真正理解生产中服务的整个静态文件。恐怕我无法向您指出不需要信用卡信息的任何其他方向。看看数字海洋或谷歌云!祝你好运。如果您找到任何方法来完成它,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2016-04-11
    相关资源
    最近更新 更多