如何在heroku django上上传和使用图片

How to upload and use images on heroku django

所以我制作了这个应用程序,您可以在其中制作产品。当我在本地使用此应用程序时,这些产品的图像已保存在文件中。我在 heroku 和 ofc 上部署了我的应用程序,因为没有像 localy 这样的普通文件,它不能保存在那里。我怎样才能保存它并使用它?我还使用 postgesql btw 来存储其他数据,所以也许我也可以存储图像。

class Product(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255, blank=True, null=True)
    image = models.ImageField(upload_to='images', blank=True, null=True)
    price = models.FloatField(max_length=255, blank=True, null=True)
    description = models.TextField(max_length=255, blank=True, null=True)
    category = models.ForeignKey(Category, blank=True, on_delete=models.CASCADE)
    seller = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

heroku 无法保存我们需要在某处托管文件的静态文件。 如果您想使用免费的静态文件提供程序,那么您可以查看 https://pypi.org/project/django-cloudinary-storage/ .. 还有另一个是 AWS S3 存储桶,我们也可以使用它,但它会向我们收取 1 美元一年的费用 ..

云端设置:

pip 安装 django-cloudinary-storage

#导入 setting.py

导入云端 进口 cloudinary.uploader 导入 cloudinary.api

INSTALLED_APPS = [ ………… 'cloudinary_storage', 'cloudinary',

]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'

#如果你去https://cloudinary.com/documentation/django_integration你可以获得钥匙

CLOUDINARY_STORAGE = { 'CLOUD_NAME': '', 'API_KEY': '', 'API_SECRET': '' }

##########

然后再次部署

我尝试了您的流程,但没有成功,因为 heroku 要求添加 cloudinary add-on,这只能通过信用卡验证 heroku 帐户才能实现,但是在印度,您无法添加信用卡或在 Heroku 上进行计费处理。