152π
I confused STATIC_ROOT and STATICFILES_DIRS
Actually I was not really understanding the utility of STATIC_ROOT. I thought that it was the directory on which I have to put my common files. This directory is used for the production, this is the directory on which static files will be put (collected) by collectstatic.
STATICFILES_DIRS is the one that I need.
Since Iβm in a development environment, the solution for me is to not use STATIC_ROOT (or to specify another path) and set my common files directory in STATICFILES_DIRS:
#STATIC_ROOT = (os.path.join(SITE_ROOT, 'static_files/'))
import os
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATICFILES_DIRS = (
os.path.join(SITE_ROOT, 'static/'),
)
Also donβt forget to from django.conf import settings
58π
There could be only two things in settings.py
which causes problems for you.
1) STATIC_URL = '/static/'
2)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
and your static files should lie under static directory which is in same directory as projectβs settings file.
Even then if your static files are not loading then reason is , you might have kept
DEBUG = False
change it to True (strictly for development only). In production just change STATICFILES_DIRS
to whatever path where static files resides.
- [Django]-How to execute a Python script from the Django shell?
- [Django]-A field with precision 10, scale 2 must round to an absolute value less than 10^8
- [Django]-Auto-create primary key used when not defining a primary key type warning in Django
44π
Serving static files can be achieved in several ways; here are my notes to self:
- add a
static/my_app/
directory tomy_app
(see the note about namespacing below) - define a new top level directory and add that to STATICFILES_DIRS in settings.py (note that
The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
)
I prefer the first way, and a setup thatβs close to the way defined in the documentation, so in order to serve the file admin-custom.css
to override a couple of admin styles, I have a setup like so:
.
βββ my_app/
βΒ Β βββ static/
βΒ Β βΒ Β βββ my_app/
βΒ Β βΒ Β Β Β βββ admin-custom.css
βΒ Β βββ settings.py
βΒ Β βββ urls.py
βΒ Β βββ wsgi.py
βββ static/
βββ templates/
βΒ Β βββ admin/
βΒ Β Β Β βββ base.html
βββ manage.py
# settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
This is then used in the template like so:
# /templates/admin/base.html
{% extends "admin/base.html" %}
{% load static %}
{% block extrahead %}
<link rel="stylesheet" href="{% static "my_app/admin-custom.css" %}">
{% endblock %}
During development, if you use django.contrib.staticfiles [ed: installed by default], this will be done automatically by runserver when DEBUG is set to True [β¦]
When deploying, I run collectstatic
and serve static files with nginx.
The docs which cleared up all the confusion for me:
STATIC_ROOT
The absolute path to the directory where collectstatic will collect static files for deployment.
β¦it is not a place to store your static files permanently. You should do that in directories that will be found by staticfilesβs finders, which by default, are βstatic/β app sub-directories and any directories you include in STATICFILES_DIRS).
https://docs.djangoproject.com/en/1.10/ref/settings/#static-root
Static file namespacing
Now we might be able to get away with putting our static files directly in my_app/static/ (rather than creating another my_app subdirectory), but it would actually be a bad idea. Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those static files inside another directory named for the application itself.
STATICFILES_DIRS
Your project will probably also have static assets that arenβt tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files.
- [Django]-Can I access constants in settings.py from templates in Django?
- [Django]-How do you detect a new instance of the model in Django's model.save()
- [Django]-How to pull a random record using Django's ORM?
15π
If your static URL is correct but still:
Not found: /static/css/main.css
Perhaps your WSGI problem.
β‘ Config WSGI serves both development env and production env
==========================project/project/wsgi.py==========================
import os
from django.conf import settings
from django.contrib.staticfiles.handlers import StaticFilesHandler
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
if settings.DEBUG:
application = StaticFilesHandler(get_wsgi_application())
else:
application = get_wsgi_application()
- [Django]-Render HTML to PDF in Django site
- [Django]-Login Page by using django forms
- [Django]-Creating email templates with Django
8π
- You can remove the
STATIC_ROOT
line - Or you can create another
static
folder in different directory. For suppose the directory is:project\static
Now update:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'project/static/')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Whatever you do the main point is STATICFILES_DIRS
and STATIC_ROOT
should not contain same directory.
I know itβs been a long time but hope the new buddies can get help from it
- [Django]-Django Admin app or roll my own?
- [Django]-Django ModelForm: What is save(commit=False) used for?
- [Django]-ImportError: cannot import name 'β¦' from partially initialized module 'β¦' (most likely due to a circular import)
6π
STATICFILES_DIRS
is used in development and STATIC_ROOT
in production,
STATICFILES_DIRS
and STATIC_ROOT
should not have same folder name,
If you need to use the exact same static folder in development and production, try this method
include this in settings.py
import socket
HOSTNAME = socket.gethostname()
# if hostname same as production url name use STATIC_ROOT
if HOSTNAME == 'www.example.com':
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
else:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/'),
]
- [Django]-Error: could not determine PostgreSQL version from '10.3' β Django on Heroku
- [Django]-How can I check the size of a collection within a Django template?
- [Django]-Unique fields that allow nulls in Django
5π
Another error can be not having your app listed in the INSTALLED_APPS
listing like:
INSTALLED_APPS = [
# ...
'your_app',
]
Without having it in, you can face problems like not detecting your static files, basically all the files involving your app. Even though it can be correct as suggested in the correct answer by using:
STATICFILES_DIRS = (adding/path/of/your/app)
Can be one of the errors and should be reviewed if getting this error.
- [Django]-Django dynamic forms β on-the-fly field population?
- [Django]-Django-Bower + Foundation 5 + SASS, How to configure?
- [Django]-Django Admin Form for Many to many relationship
4π
In your cmd type command
python manage.py findstatic --verbosity 2 static
It will give the directory in which Django is looking for static files.If you have created a virtual environment then there will be a static folder inside this virtual_environment_name folder.
VIRTUAL_ENVIRONMENT_NAME\Lib\site-packages\django\contrib\admin\static
.
On running the above βfindstaticβ command if Django shows you this path then just paste all your static files in this static directory.
In your html file use JINJA syntax for href and check for other inline css. If still there is an image src or url after giving JINJA syntax then prepend it with β/staticβ.
This worked for me.
- [Django]-VueJS + Django Channels
- [Django]-Annotate a queryset with the average date difference? (django)
- [Django]-FileUploadParser doesn't get the file name
- [Django]-How can I use the variables from "views.py" in JavasScript, "<script></script>" in a Django template?
- [Django]-Is it better to use path() or url() in urls.py for django 2.0?
- [Django]-Copy a database column into another in Django
2π
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')
STATICFILES_DIRS=[STATIC_DIR]
- [Django]-When to use get, get_queryset, get_context_data in Django?
- [Django]-How to run own daemon processes with Django?
- [Django]-Row level permissions in django
2π
Always remember two things in Django at the end of file settings.py
For development
STATIC_URL = '/static/'
For production
STATIC_ROOT = '/static/'
Since you are working in a development environment, comment out the other two paths from settings.py
file
#STATIC_ROOT = '/home/glide/Documents/django/cbox/static/'
STATIC_URL = '/static/'
#STATICFILES_DIRS = (
# '/static/',
#)
And for the urls.py
make changes as follows
urlpatterns = patterns('',
...
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root', settings.STATIC_URL}
),
...
);
Hope this may solve the problems
- [Django]-How to get an ImageField URL within a template?
- [Django]-Django 2.0 β Not a valid view function or pattern name (Customizing Auth views)
- [Django]-Complete django DB reset
2π
Django does not have a built-in solution for serving static files, at least not in production when DEBUG has to be False.
We have to use a third-party solution to accomplish this.
To install WhiteNoise in your virtual environment, type the command below:
pip install whitenoise
then Modify Settings
To make Django aware of you wanting to run WhitNoise, you have to specify it in the MIDDLEWARE list in settings.py file:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
].
- [Django]-Django Rest Framework β Updating a foreign key
- [Django]-Django migration fails with "__fake__.DoesNotExist: Permission matching query does not exist."
- [Django]-How can I build multiple submit buttons django form?
1π
I found that I moved my DEBUG
setting in my local settings to be overwritten by a default False
value. Essentially look to make sure the DEBUG setting is actually false if you are developing with DEBUG
and runserver
.
- [Django]-Effects of changing Django's SECRET_KEY
- [Django]-Why does DEBUG=False setting make my django Static Files Access fail?
- [Django]-How to set environment variables in PyCharm?
1π
If you are on development environment you will need to define STATIC_URL
and STATICFILES_DIR
and if you are on production environment you need to define STATIC_URL
and STATIC_ROOT
For windows:
STATIC_URL = 'static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
And for linux environment
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATICFILES_DIRS = (os.path.join(SITE_ROOT, 'static'),)
- [Django]-How to access a dictionary element in a Django template?
- [Django]-Django Rest Framework model serializer with out unique together validation
- [Django]-Django β Circular model import issue
0π
If youβve have added the django-storages
module (to support uploading files to S3 in your django app for instance), and if like me you did not read correctly the documentation of this module, just remove this line from your settings.py
:
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
Otherwise it will cause your static assets to be looked NOT on your local machine but remotely in the S3 bucket, including admin panel CSS, and thus effectively breaking admin panel CSS.
- [Django]-Django url tag multiple parameters
- [Django]-How to access Enum types in Django templates
- [Django]-Where to put business logic in django
0π
You need only for Development:
STATIC_URL = '/staticfiles/'
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'staticfiles'),
)
For Production (when using /manage.py collectstatic):
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
After Debug = False your static files will not loading. You can check it via entering to 127.0.0.1:8000/staticfiles/css/main.css (for example).
So, you need change to Debug = True and then reload the page via Ctrl+F5.
- [Django]-What is the purpose of apps.py in Django 1.9?
- [Django]-How do I install psycopg2 for Python 3.x?
- [Django]-Macros in django templates