Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Heroku for Django Media Files

Tags:

django

heroku

On the heroku domain, I am not able to load my Media(Images Saved by using ImageField property) file images. However, I am able to see the images saved in the static field if I set debug = True

I save my images using the following command:

image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field = "height_field")

And I am able to reference them in my template by doing someething like this:

<img src="{{ instance.image.url }}" class="img-responsive">

Where instance is passed from my views.py like so:

instance = get_object_or_404(Post,slug=slug)
if instance.draft or instance.publish > timezone.now().date():
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404
share_string = quote_plus(instance.content)
context = {
    "title": "Detail",
    "instance": instance,
    "share_string":share_string,
}
return render(request,"post_detail.html",context)

Thanks

like image 865
anderish Avatar asked Jan 04 '17 22:01

anderish


People also ask

How do I host a Django media file?

Unfortunately, the Django development server doesn't serve media files by default. Fortunately, there's a very simple workaround: You can add the media root as a static path to the ROOT_URLCONF in your project-level URLs.

Can Heroku store static files?

Storing static files elsewhere is crucial for Heroku apps since dynos have an ephemeral filesystem. Whenever you replace a dyno or when it restarts, which happens daily, all files that aren't part of your application's slug are lost. Use a storage solution like S3 to offload the storage of static files from your app.

Can I use Django with Heroku?

When you deploy to Heroku, the dependencies you specify in your requirements. txt file are automatically installed before app startup. If you're using Django, the collectstatic command also runs automatically during the deployment process.


1 Answers

The Heroku filesystem is ephemeral, so dynos boot with a clean copy of the filesystem from the most recent deploy. Here are some ways to work around this:

  1. AWS S3
  2. If you don't want to set up an account with AWS to create an S3 bucket, Heroku has add-ons that handle storage and processing of static assets

For more details on this issue, see https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted

like image 155
omar ahmed Avatar answered Sep 19 '22 10:09

omar ahmed