What's the difference between STATIC_URL and STATIC_ROOT in Django?

Izzo picture Izzo · Jun 9, 2016 · Viewed 9.1k times · Source

I'm somewhat confused as to what the difference is between STATIC_URL and STATIC_ROOT in Django's 'staticfiles' app.

I believe I understand what the STATIC_ROOT is: it's essentially the location on the server where the staticfiles' collectstatic command will place the static files collected from your django project. The collectstatic command searches in the locations that you specify in the STATIC_FINDERS setting.

However, what exactly does the STATIC_URL do? What should this be set to? Apparently it's intended to be set something such that users can access static files. But what is it's relationship with STATIC_ROOT?

Why is the default value of STATIC_URL simply /static/ ? Does STATIC_URL have to be able to reference STATIC_ROOT?

Answer

AKS picture AKS · Jun 9, 2016

Like you mentioned, it is pretty clear from the documentation:

STATIC_ROOT:

The absolute path to the directory where collectstatic will collect static files for deployment.

STATIC_URL

default: None

URL to use when referring to static files located in STATIC_ROOT.

Example: "/static/" or "http://static.example.com/"

While, the STATIC_ROOT is just the path to the directory where static files have been collected, STATIC_URL is the URL which will serve those static files.

And, as you can see in the example, you can define STATIC_URL as a subdomain "http://static.example.com/" and when you use it in the template:

<link rel="stylesheet" href="{{ STATIC_URL }}css/base.css" type="text/css" />

It will be treated as:

<link rel="stylesheet" href="http://static.example.com/css/base.css" type="text/css" />

But, if the STATIC_URL was just /static/ then the above link would point to:

<link rel="stylesheet" href="/static/css/base.css" type="text/css" />

And, since this href starts with / it will append your domain to access the static files: http://yourdomain/static/css/base/css


Why is the default value of STATIC_URL simply /static/ ? Does STATIC_URL have to be able to reference STATIC_ROOT?

Default value of STATIC_URL is not /static/ but None as you can see in the documentation. And, it doesn't have to reference to STATIC_ROOT because it is not dependent on it (as shown in the example above).