I have read the Django docs and I seemed to have understood how STATIC_URL woks and its purpose.
But then I saw an example, tried it and now I’m back to square one - not understanding STATIC_URL at all.
I have set STATIC_URL = '/static/abcd/'
, basically just an arbitrary path and Django still correctly fetches static files. For example, it is serving a CSS file from <link rel="stylesheet" href="/static/abcd/css/app.css" type="text/css">
as seen in the DevTools although there is no such directory on my system. My CSS file is in common_static/css/app.css
and is collected to static/css/app.css
.
How is this possible?
What’s the content of your STATICFILES_DIRS
setting?
Tip: Use the static template tag to reference static files in your templates.
+<link rel="stylesheet" href="{% static 'css/app.css' %}" type="text/css">
-<link rel="stylesheet" href="/static/abcd/css/app.css" type="text/css">
What’s the content of your
STATICFILES_DIRS
setting?
STATIC_DIR = os.path.join(BASE_DIR, 'common_static')
STATIC_URL = '/static/abcd/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [STATIC_DIR, ]
Tip: Use the [static] template tag to reference static files in your templates.
Sorry for the confusion, I do use {%static%}
template tag in the base.html template like this:
<link rel="stylesheet" href="{% static "css/app.css" %}" type="text/css">
.
But then when I open the web page in the browser and inspect it in the DevTools to see where the browser is actually fetching the CSS file from, that’s what I see:
<link rel="stylesheet" href="/static/abcd/css/app.css" type="text/css">
And if I do “Copy Link Address” from the DevTools, I get:
http://localhost:8000/static/abcd/css/app.css
But like I mentioned, this path does not exist on my server, so I’m not sure how this is possible.
Two things - first, if you’re running in development mode using runserver (or runserver_plus), Django will fetch your static files from within your project structure. (See Serving static files in development.
Second, and this is universally true - there is no requirement that a URL represent an actual path on a server. A URL is just a request to a server for a resource. It’s up to the server to determine what resource to retrieve for each request. (In fact, more often than not, they don’t.) In the case of static files, the server maps that static url to an actual directory.