zerohedge
zerohedge

Reputation: 3765

Django Heroku: No Such File or Directory for image (image is in repo)

I'm using the following to attach a picture (which is committed with the Github repo) to an email:

twitter_image = MIMEImage(open(get_static('img/twitter.png'), 'rb').read(), _subtype='png')
twitter_image.add_header('Content-ID', '<{}>'.format('twitter.png'))

get_static is defined as:

from django.contrib.staticfiles.finders import find
from django.contrib.staticfiles.templatetags.staticfiles import static

def get_static(path):
    if settings.DEBUG:
        return find(path)
    else:
        return static(path)

The same code is working in another project perfectly both in development and in production. But for some reason it's failing on Heroku with this project, when I run the email function on Heroku it returns an error like:

Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/code.py", line 91, in runcode
    exec(code, self.locals)
  File "<console>", line 1, in <module>
  File "/app/notifications/models.py", line 75, in email_users
    twitter_image = MIMEImage(open(get_static('img/twitter.png'), 'rb').read(), _subtype='png')
FileNotFoundError: [Errno 2] No such file or directory: '/static/img/twitter.6a4fa62e22f6.png'

Upvotes: 1

Views: 327

Answers (1)

zerohedge
zerohedge

Reputation: 3765

Daniel Roseman got me off the right direction:

I'm not sure what you're doing here, but you seem to be confusing URLs and file paths. Is DEBUG true or false? – Daniel Roseman

This is what I should use:

from django.contrib.staticfiles.storage import staticfiles_storage
MIMEImage(open(staticfiles_storage.path('img/twitter.png'), 'rb').read(), _subtype='png')

Upvotes: 1

Related Questions