Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using relative vs absolute URL for STATIC_URL in Django

Tags:

python

django

I'm attempting to setup appropriate STATIC_URL and STATIC_ROOT values for a new Django project, and I'm running into a problem with using an absolute URL for STATIC_URL.

My project is structured like:

<project root>
    static
    media
    src
        <apps>
        static
            js
            css
                custom.css
            i
        settings.py

In my settings.py, I have

STATIC_ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../static/'))

If I set STATIC_URL = '/static/', then I can access http://localhost:8000/static/css/custom.css perfectly.

However, if I use an absolute URL like STATIC_URL = 'http://localhost:8000/static/', as though I were using a CDN, then http://localhost:8000/static/css/custom.css returns a 404 error.

Shouldn't these settings be effectively identical? The docs state STATIC_URL can be absolute. Why does the later setting fail to load static media?

like image 851
Cerin Avatar asked May 15 '13 19:05

Cerin


2 Answers

I just tested the same thing, using http://localhost:8000/static/ doesn't work for me either.

In my settings I keep a development variable, so on localhost the url is '/static/' and when I'm deployed (and I set DEVELOPMENT = False), its a full url.

if DEVELOPMENT == True:
    STATIC_URL = '/static/'
else:
    STATIC_URL = 'https://www.mywebsite.com/static/'
like image 155
cjd82187 Avatar answered Nov 03 '22 01:11

cjd82187


I assume that you are using the static function from the django.conf.urls.static to serve your static files in the development environment (that means DEBUG=True). Now as you can read in the documentation this function is not working with the absolute urls with DEBUG enabled.

So from the docs:

https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-during-development

"This helper function works only in debug mode and only if the given prefix is local (e.g. /static/) and not a URL (e.g. http://static.example.com/)."

like image 3
jbub Avatar answered Nov 03 '22 02:11

jbub