how to point correctly to static image in django

Atma picture Atma · Mar 27, 2014 · Viewed 32.5k times · Source

I have a template that renders an image:

{% load staticfiles %}

<img src="{% static "img/logo.png" %}" alt="My image"/>

The image link is broken, but it points to:

localhost/static/img/logo.png

What are values I need to set for static_root, static_url, and STATICFILES_DIRS to get this image to show up correctly?

This is my directory structure:

myprojectname (top level)

--- myprojectname

--- --- myproectname

--- --- --- settings

--- --- --- --- base.py (setting.py)

--- --- static

--- --- --- img

This is my static configuration in settings:

STATIC_ROOT = '/Users/myuser/myprojectname/myprojectname'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    #normpath(join(SITE_ROOT, 'static')),
    os.path.join(BASE_DIR, "static"),
    '/Users/myuser/myprojectname/myprojectname/static',
)

This is what it shows: enter image description here

I have already done a collectstatic and this doesn't work.

Answer

Brandon picture Brandon · Apr 1, 2014

Static files can be confusing in Django. I'll try to explain as simply as possible...

STATIC_ROOT This is the directory that you should serve static files from in production.

STATICFILES_DIRS This is the directory that you should serve static files from in development.

STATIC_ROOT and STATICFILES_DIRS cannot point to the same directory.

Django is a highly modular framework. Some application modules contain their own templates, css, images and JavaScript. Django admin is one such app. Django extends this modularity to applications you create by using different directories for static files in development versus production.

When DEBUG = True and you have included django.core.staticfiles in your INSTALLED_APPS, Django will serve the files located in the STATICFILES_DIRS tuple using the STATIC_URL path as the starting point.

In production this responsibility should be given to Nginx, Apache, CloudFront, etc. When DEBUG = False, Django will not automatically serve any static files.

When you run:

$ python manage.py collectstatic

The files specified in the STATICFILES_DIRS are copied into the STATIC_ROOT to be deployed.

So, to answer your question, I would do the following:

Create another directory to store your static files in development and add that path to your STATICFILES_DIRS. I usually call this folder "static-assets". It can reside at the same level as your existing "static" directory.

Set STATIC_ROOT to the path to your existing "static" directory.

If you look closely at the path that's returning a 404 in your screenshot, the image path is specified as: /static/img/logo.png, but your directory for images is: /static/image/

So double-check your image path to make sure you're pointing to the right directory.