So I've never deployed a Django app and I'm trying to get up to speed on the whole thing. I ran the collectstatic command and now non of my static files will render. When I run the findstatic command I receive an exception that says:
django.core.exceptions.ImproperlyConfigured: The storage backend of the staticfiles finder <class 'django.contrib.staticfiles.finders.DefaultStorageFinder'> doesn't have a valid location.
My template renders just find but I can't seem to figure out why the css file is not being found. Highlight from my settings module:
settings/
base.py
devel.py
prod.py
base.py
cwd = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = cwd[:-9] # chop off "settings/"
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
]
TEMPLATE_LOADERS = [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django.template.loaders.eggs.Loader',
]
TEMPLATE_DIRS = [
os.path.join(PROJECT_ROOT, "templates"),
]
devl.py
STATIC_URL = "/site_media/static/"
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, "site_media", "static"),
]
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media", "static")
site_base.html
<link rel="stylesheet" href="{{ STATIC_URL }}css/site_base.css" />
Would appreciate your help because Im stumped.
Update:
It turned out to be a missing context processor. To get your STATIC_URL setting inside a template, you have to register the staticfiles context processor:
TEMPLATE_CONTEXT_PROCESSORS = [
...
'django.core.context_processors.static',
...
]
First stab:
It looks like you'll need to add that dir to your list of static sources (re: a comment above):
# list of input paths for collectstatic
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, "tulsa", "static"),
# you'll want to remove this path:
#os.path.join(PROJECT_ROOT, "site_media", "static"),
]
# output path for collectstatic
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media", "static")
Related
I have an API that delivers images and puts them in a folder. I want to make that folder accessible via Django.
folder structure:
- theProject
- static
settings.py
urls.py
.
.
.
- theApp
- apiimagesfolder
views.py
forms.py
urls.py
.
.
.
I tried adding the apiimagesfolder folder to my static dirs:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "theProject", "static"),
os.path.join(BASE_DIR, "theApp", "apiimagesfolder"),
]
and I tried accessing an image in apiimagesfolder on the debug server with 127.0.0.1:8000/imagename.bmp but failed. What would the correct path be?
Is the path staying the same after deploying?
Try this:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "apiimagesfolder"),
]
I'm trying to serve static files in my product review website, and I'm using Whitenoise, but It didn't work (can not find the files in /static) (when I test on local with DEFAULT = False, it still works)
I've tried to config wsgi file instead of using whitenoise middleware
This is my some code in my settings file to serve static.
DEBUG = False
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'djangobower.finders.BowerFinder',
)
Can you show me how to fix it? Pardon for my English
I tried to config the settings again:
DEBUG = False
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# I don't have STATICFILES_DIRS, is it wrong?
STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage"
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'djangobower.finders.BowerFinder',
)
But it still can not serve static files
I believe what you're missing is the STATICFILES_STORAGE. This is my settings.py related configuration.
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
ALLOWED_HOSTS = ["*"]
I followed the below configuration settings to resolve the issue.
DEBUG = False
ALLOWED_HOSTS = ['testnewapp.herokuapp.com']
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'widget_tweaks',
'phonenumber_field',
'django_extensions',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
# Whitenoise Storage Class - Apply compression but don’t want the caching behaviour
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
# Comment the below line
# django_heroku.settings(locals())
Things to Remember
Make sure you’re using the static template tag to refer to your static files, rather that writing the URL directly. For example:
{% load static %}
<img src="{% static "images/error.jpg" %}" alt="OOps!" />
<!-- DON'T WRITE THIS -->
<img src="/static/images/error.jpg" alt="OOps!" />
If you get an error message with collectstatic, simply disable it by instructing Heroku to ignore running the manage.py collecstatic command during the deployment process.
But if you need to use WhiteNoise with any WSGI application
You need to wrap your existing WSGI application in a WhiteNoise instance and tell it where to find your static files. For example:
from my_project import MyWSGIApp
application = MyWSGIApp()
application = WhiteNoise(application, root='/path/to/static/files')
application.add_files('/path/to/more/static/files', prefix='more-files/')
Note
These instructions apply to any WSGI application. However, for Django applications you would be better off using the WhiteNoiseMiddleware class which makes integration easier.
#
http://whitenoise.evans.io/en/stable/base.html
When I load my local site I cannot get the CSS files to load. I'm running Django 1.9 and python 3.4.2.
Here is my structure:
apps/
app1/
app2/
etc.
clients/
media/ #css, js, images, etc.
static/ #static files
templates/ #html templates
__init__.py
manage.py
settings.py
etc.
In my settings.py file I have:
STATIC_ROOT = os.path.join(BASE_DIR, 'clients', 'static')
STATIC_URL = 'clients/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'clients', 'media'),
]
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'clients', 'media')
And my html template that is calling the css files is as so:
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/primary_stylesheet.css' %}" />
I continue to get a 404 error that says it can't find the css file in:/clients/static/css/primary_stylesheet.css
In my settings.py file I have printed out my STATICFILES_DIRS and STATIC_ROOT and they both lead directly where they should. I've read through the documentation and tried multiple variations of DIRS and ROOT and don't understand why the css file is not pulling correctly - even "collectstatic" is collecting correctly.
I greatly appreciate any help and wisdom someone else has to give.
Thank you!
If you have DEBUG = True set then django won't actually pull your files from the /static/ folder - it finds and collects your staticfiles at runtime when you input the runserver command.
I think you'll find that if you use the default setting for STATICFILES_FINDERS your app will be able to serve your files:
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
If you are running your server with python ./manage.py runserver, you need to set urls for both static and media files, check here: https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-static-files-during-development
When I am starting a new project, I generally set my urls.py like this:
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url, include
from django.contrib import admin
url_patterns = [
url(r'^admin/', admin.site.urls),
# your url patterns go here
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This requires you to set STATIC_ROOT, STATIC_URL, MEDIA_ROOT and MEDIA_URL in your settings.py:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static_files'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I have a problem. I did everything as described in this Django tutorial (EDIT: dead link, here's a working link), and everything is running fine, but CSS and images are not showing up/being applied. How do I get the CSS and images to show up properly? Thanks for any help.
My CSS style file:
li a {
color: red;
}
body {
background: white url("images/background.gif") no-repeat right bottom;
}
urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns,url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
index.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static '/polls/style.css' %}"/>
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li>{{ poll.question }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
settings.py
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
'/polls/static/'
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
TEMPLATE_DIRS = (
'C:/django poll project/mysite/templates',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'polls',
)
On runserver command, getting:
[18/Sep/2014 17:40:51] "GET /polls/ HTTP/1.1" 200 311
[18/Sep/2014 18:25:39] "GET /polls/ HTTP/1.1" 200 311
Updated Answer For Django 2.2 - 2019
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
BASE_DIR is already defined in settings.py
Also when loading, do {% load static %} instead of {% load staticfiles %}
The URL to the static-Files is "yourDomain/static/"
When you want to access to your "style.css" you should use "/static/style.css" instead of "/polls/style.css"
EDIT:
Change this part of your settings.py
STATICFILES_DIRS = (
'/polls/static/'
)
to
STATICFILES_DIRS = (
'C:/django poll project/mysite/static'
)
better would be:
STATICFILES_DIRS = (
os.path.join(SITE_ROOT, '..', 'static'),
)
Then the folder is called "static" and is on the same level where the "manage.py" is. When you put your style.css in this "static"-folder you can call it with "/static/style.css"
It worked for me :
PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, '..', 'static'),
)
for Django version 4 2022
if anyone's static file is not working,make sure your static folder is in the right location
shortcut:
Keep your static folder in the same directory where your database is located.
-->ProjectName
-->app1
-->app2
-->db.sqlite3
-->static
and make sure you have added this lines in settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = (
BASE_DIR/'static',
)
Following the documentation: https://docs.djangoproject.com/en/3.2/howto/static-files/
And restarting the server worked for me
If problem bad variable {{STATIC_URL}} in template files, add
'django.template.context_processors.static'
to this part of settings.py module:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': TEMPLATE_DIRS,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'images')
Remove django.contrib.staticfiles from INSTALLED_APPS.
Set STATIC_ROOT to the drive folder with the static files.
Set STATIC_URL to the browser folder/prefix that will point at the files.
The problem is STATIC_ROOT and STATICFILES_DIRS cannot be in the same folder and try to act differently...
STATICFILES_DIRS
exists because different installable apps have different static resources.
Through django magic, in development these files are served from each app.
This allows editing assets and re-running the server without worrying about the STATIC_ROOT cache.
Also requires a collector that assembles static files into STATIC_ROOT.
STATIC_ROOT
The place the files are served from in production.
A simple browser path to folder mapping.
Not recommended for production because usually NGINX or AppEngine handles this.
Works because you are skipping the collector and telling Django to look here always.
Will not work if an app has its own assets, you will need to use STATIC_DIRS.
Currently works on Django Version 3.x
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Website</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<h1>Hello user!</h1>
<p>something you want</p>
</body>
</html>
To work above Implementation Following code must be added in project setting file.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
Here static is a directory in project root.
When you run 'python manage.py runserver' add any post number like 2000 or whatever it will look like 'python manage.py runserver 2000' it will solve the problem
So I updated my project settings with the following scheme
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
/settings
base.py
prod.py
dev.py
Is this the correct STATICFILES_DIRS settings for the above configuration?
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, "site_media", "static"),
]
STATIC_URL = "/site_media/static/"
The templates render just fine using
TEMPLATE_DIRS = [
os.path.join(PROJECT_ROOT, "templates"),
]
So I'm a little turned around as to why my css files arent working
Home.html
<link rel="stylesheet" href="{{ STATIC_URL }}css/home.css" />
You might want to change your PROJECT_ROOT to something like this:
# cwd is settings. determine project path
cwd = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = cwd[:-9] # chop off "settings/"
That should get your project root where you want it. Also, what link is being created on the front end when you try to use {{STATIC_URL}}?
You might want to check out this link for more information on splitting up the settings.py file.