Using relative absolute URLs for STATIC_URL in Django

I'm trying to set the appropriate STATIC_URL and STATIC_ROOT values ​​for a new Django project, and I am having trouble using the absolute URL for STATIC_URL.

My project is structured as:

<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, for example STATIC_URL = 'http://localhost:8000/static/' , as if I used the CDN, then http://localhost:8000/static/css/custom.css returns a 404 error .

Shouldn't these settings be virtually the same? The state of docs STATIC_URL may be absolute. Why doesn’t the static media load in later settings?

+4
source share
3 answers

I just tested the same thing, using http://localhost:8000/static/ does not work for me either.

In my settings, I save the development variable, so the localhost url is '/ static /', and when I expand (and I set DEVELOPMENT = False ), its full URL.

 if DEVELOPMENT == True: STATIC_URL = '/static/' else: STATIC_URL = 'https://www.mywebsite.com/static/' 
+5
source

I assume that you are using the static function from django.conf.urls.static to serve your static files in the development environment (this means DEBUG=True ). Now, as you can read in the documentation, this function does not work with 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 only works in debug mode and only if the given prefix is ​​local (for example, / static /), and not a URL (for example, http://static.example.com/ )."

+2
source

The reason and solution was simple, but discovering it was not intuitive, based on how I described the problem. I did not mention that my absolute STATIC_URL really had a different domain ( http://localmedia:8000/static/ not http://localhost:8000/static/ ).

I did this as part of a hack to simplify media hosting among several external Windows machines that I used to test different versions of IE.

However, if there is a mismatch between the domain in the local domain of STATIC_URL and runserver's , Django only services content from STATIC_ROOT and does not attempt to extract media from application folders. Not sure why, but as it is.

If I run manage.py collectstatic , it will effectively fix the 404 error by copying all the files to the application folder in my STATIC_ROOT. Alternatively, I could use the same domain in my STATIC_URL , and Django will automatically detect any unsaved media in the application folders.

0
source

Source: https://habr.com/ru/post/1481021/


All Articles