Home > other >  How to upload and use images on heroku django
How to upload and use images on heroku django

Time:11-07

so i make this app in which you can make products. And those products have an image that was saved in a file while i was using this app localy. I deployed my app on heroku and ofc since there are no normal files like localy it cant be saved there. How can i save it somewere and use it? I also use postgesql btw to store other data so maybe i can store the image too.

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

CodePudding user response:

heroku can't hold our static files we need to host our files somewhere . If you want to use a free static file provider then you can check out https://pypi.org/project/django-cloudinary-storage/ .. There is another one which is AWS S3 bucket we can use it too but it will charge us 1$ for a year ..

cloudinary setup :

pip install django-cloudinary-storage

#import in setting.py

import cloudinary import cloudinary.uploader import cloudinary.api

INSTALLED_APPS = [ ....... 'cloudinary_storage', 'cloudinary',

]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'

#if you go to https://cloudinary.com/documentation/django_integration you can get keys

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

##########

and then deploy it again

  • Related