99lives
99lives

Reputation: 848

Django: Where to store global static files and templates?

So I am working on a Django (1.9) project, and have the need to use the same templates and static files across multiple apps. I know how to use templates and static files stored outside each app (using STATICFILES_DIRS and TEMPLATEFILES_DIRS in settings.py), but where should I store them?

My guess would be in folders in the project directory.

home/user/myproject/staticfiles
home/user/myproject/templates

But if there are official reconsiderations (which I have been unable to find in the documentation), I would prefer to comply with those.

Also, if there are any other recommendations for using templates and static files outside of the normal django app directories, that you think I should know about, I'd really appreciate you telling me (or telling me where to look).

Cheers :)

Upvotes: 29

Views: 14997

Answers (3)

david
david

Reputation: 419

While nu everest's answer is correct and working (after you restart the server), in my case it lacks the advantage of my IDE autosuggesting the static files' paths. So I went for specifying a relative path inside my project. For simplicity I named the directory 'static' (same as the STATIC_URL variable) but of course any name is possible.

settings.py:

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    "myproject" + STATIC_URL
]

What's important here: The root is actually not the settings.py's parent, but its parents's parent, as in:

BASE_DIR = Path(__file__).resolve().parent.parent

Upvotes: 1

nu everest
nu everest

Reputation: 10249

Assume there is a global css file located here: home/user/myproject/staticfiles/css/global.css

Change settings.py to match this:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "staticfiles"), 
]

Inside of a template, for example, index.html:

{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'css/global.css' %}" />   

Now Django can find global.css.

Upvotes: 32

Khaled Al-Ansari
Khaled Al-Ansari

Reputation: 3970

in your settings.py file add the following

STATIC_URL = '/static/' # this will be added before your file name
STATIC_ROOT = 'path/to/your/files/' # this will help django to locate the files

read more about it here: https://docs.djangoproject.com/en/1.9/howto/static-files/

Upvotes: 1

Related Questions