Serving Django`s static/media files via IBM Cloud Foundry

77 Views Asked by At

Using IBM Cloud Foundry service for deployment, I am trying to find a way to serve static/media files with Django in DEBUG=False mode. When deploy, I get a fully functional app with working js and css except media files. My configs:

manifest.yml

  applications:
  - name: onlinecourse
    routes:
      - route: $HOST.$DOMAIN
    memory: 128M
    buildpack: python_buildpack
  - name: onlinecourse-nginx
    routes:
      - route: $HOST.$DOMAIN/static
    memory: 64M
    buildpack: staticfile_buildpack

Notice second app 'onlinecourse-nginx' serves static via '$HOST.$DOMAIN/static' and use pre-configured staticfile_buildpack with nginx start up somewhere inside, so probably that is a 'devil' here. (I run 'python3 manage.py collectstatic' beforehand, by the way.)

models.py

class Course(models.Model):
    ...
    image = models.ImageField(upload_to='course_images/')
    ...

settings.py

INSTALLED_APPS = [
....
'django.contrib.staticfiles',
]

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

urls.py

urlpatterns = [
    ....
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

some template:

<img src="{{ course.image.url }}" width="240px" height="240px" ...
                             

This gives me a link as '/media/course_images/...', and it works fine in DEBUG=True. But in DEBUG=False actual desired link is '/static/media/course_images/...' as nginx is configure with manifest.yml. How to meet them up?

My ideas:

  1. Explicitly play around with Django {% static ... %} construct and STATICFILES_DIRS config. It partially solves the problem giving /static/ prefix. But links become broken in DEBUG=True.

  2. It seems obvious to make some adjustments to nginx. But I don't see in staticfile-buildpack docs any straightforward way to feed some custom configs.

  3. Crazy way to let Django serve static even in DEBUG=False mode by himself with some ugly tricks like 'runserver --insecure'. I find it creative but probably avoidable.

Am I missing something?

0

There are 0 best solutions below