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
Related
I have just deployed (first time ever) a Django project to a web server. Everything (including postgres) works flawlessly, except that static images won't load.
Here is the relevant part of the settings.py:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
#STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static"),
#]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL = 'home'
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
AUTH_USER_MODEL = 'account.CustomUser'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
The error message I get is the following in the console:
"GET /static/images/logo.png HTTP/1.1" 404 1808
However, when checking the file path in the console I have the following:
root#melius:/django/melius/static/images#
In this folder the files are present.
Where is my mistake?
There can be two reaon your static files not working.
First of all, Django doesn't serve static files on production.
Also i notice your static settings are wrongly configured.
Make sure your setting.py is look like this:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'YOUR STATIC FILE FOLDERS')]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
If you run your application on Nginx or apache2please make sure you configured the.conf` file properly to serve the static files.
Also, there is a straightforward and easy solution, that is whitenoise
If you don't want to serve your static files with Nginx or a similar server.
You can try whitenoise
To use whitenoise, please install it first and update your settings.py file like this:
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
and add this in middlware before the sessionmiddleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # Serve static in production without nginx or apache
'django.contrib.sessions.middleware.SessionMiddleware',
........
]
Hope the solution will solve your problem
Here you go for whitenoise docs: http://whitenoise.evans.io/en/stable/
Note: static root and static dirs shound't be same
I am trying to deploy my webapp to heroku. I am using Django and the following is most of my settings.py file:
"""
Django settings for blog project on Heroku. For more info, see:
https://github.com/heroku/heroku-django-template
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import dj_database_url
import raven
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
try:
from .local_settings import *
except ImportError:
pass
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
# Disable Django's own staticfiles handling in favour of WhiteNoise, for
# greater consistency between gunicorn and `./manage.py runserver`. See:
# http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'blogapp',
'homeapp',
'nimfksapp',
'omniclipapp',
#Heroku Sentry
'raven.contrib.django.raven_compat',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'blog.urls'
WSGI_APPLICATION = 'blog.wsgi.application'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "live-static", "media-root")
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
When running collectstatic locally the static files get collected fine and are served up on the web page. When I deploy the app to heroku (which automatically runs the collectstatic command for me) it throws up an "Internal Server Error (500)". I followed a recommendation on a similar SO page and added a sentry to the app through heroku and got a clearer error message:
ValueError/nimfks/ errorMissing staticfiles manifest entry for...
I tried changing (and removing) the STATICFILES_STORAGE without success. Removing it got me past the error but trying to display the actual static file (in this case an image) didnt work i.e. it wasnt loading.
I also tried changing the static settings to use PROJECT_ROOT instead of BASE_DIR and a lot of different configurations, all of which didnt work.
Am I missing something here? I cant seem to find an answer in the similar questions asked on SO.
EDIT
Answer:
Embarrasing as it is I want to keep this up since it might help someone else struggling with this. Issue in my case was that I was using .PNG in my html file instead of .png which was the real file extension. Didn't realize this was case sensitive. The real solution to this problem was essentially just having a sentry running that will catch these types of errors (see sentry docs). This is my final version of my static settings in the settings.py file:
import os
import dj_database_url
import raven
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
WSGI_APPLICATION = 'blog.wsgi.application'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'static'),
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Try to comment the line
'django.contrib.staticfiles',
inside INSTALLED_APPS
I have been trying to create a django application, but there is a problem with django rendering static files:
Here is my setting files static configuration:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
I have placed all the static files in a static folder inside the location where manage.py resides.
Here you defined an STATIC_ROOT, so you after placing your static files and on each change of your css or js files you need to run
python manage.py collectstatic
This command will gather all static files into the defined dictionary, but this is done after the completion of development. So instead of that you can use STATICFILES_DIRS during development,
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
which will automatically find the static files during your development period.
Also make sure you have staticfiles in installed apps.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles', # it's is used for static files
]
In your template you can load static files like
{% load staticfiles %} # register static tag
<link ref="stylesheet" href="{% static 'style.css' %}">
settings.py
INSTALLED_APPS = [
...
...
'django.contrib.staticfiles',
...
...
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn")
urls.py (main project's urls.py)
from django.conf.urls.static import static
urlpatterns = [
...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
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")
I've gone and adjusted something somewhere along the line, and cant find way back.
My file structure
examplesite1
--registration
--A bunch of files well ignore
--snapboard
--static
--Associated static folders css, js etc
--templates
--snapboard
--html files
--some folders
--manage.py
--settings.py
--urls.py
--__init__.py
Im having trouble pointing the html files in templates/snapboard to the static files in snapboard/media.The code in the html is
<link type="text/css" rel="stylesheet" href="{{ SNAP_MEDIA_PREFIX }}/css/yui/reset-fonts-grids.css" />
in the settings file I have of that which i think is valid
MEDIA_ROOT = ''
MEDIA_URL = '/snapboard/'
ADMIN_MEDIA_PREFIX = '/media/admin/'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
#'django.template.loaders.eggs.load_template_source',
)
STATICFILES_DIRS = (
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
STATIC_URL = 'static/'
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.request",
"snapboard.views.snapboard_default_context",
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'pagination.middleware.PaginationMiddleware',
'snapboard.middleware.threadlocals.ThreadLocals',
'snapboard.middleware.ban.IPBanMiddleware',
'snapboard.middleware.ban.UserBanMiddleware',
)
ROOT_URLCONF = 'examplesite1.urls'
TEMPLATE_DIRS = (
)
INSTALLED_APPS = (
'examplesite1',
'registration',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.markup',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.staticfiles',
'snapboard',
'pagination',
)
SNAP_MEDIA_PREFIX = MEDIA_URL + 'static/'
# Set MEDIA_ROOT so the project works out of the box
import os
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'snapboard/media')
Ive spent bloody ages going through a process of elimination trying a ton different combinations with out success. Whats the correct way to code this.
make ur media url as MEDIA_URL = '/snapboard/' and in your code change href="{{ SNAP_MEDIA_PREFIX }}/css/yui/reset-fonts-grids.css" to href="{{ SNAP_MEDIA_PREFIX }}css/yui/reset-fonts-grids.css" because {{ SNAP_MEDIA_PREFIX }}/css/ is not same as {{ SNAP_MEDIA_PREFIX }}css/
What version of Django are you running? If it's 1.3+, you should be using the staticfiles contrib package and you app's "media" directory should be named static to allow Django to pick it up.
Otherwise, there's no support for static resources inside your apps, so you need to copy all those files into your MEDIA_ROOT directory.
UPDATED
Drop the whole SNAP_MEDIA_PREFIX business; it's unnecessary and complicating things. This is all you need:
STATIC_ROOT = os.path.join(os.path.dirname(__file__), 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'site_media')
MEDIA_URL = '/site_media/'
Never directly use STATIC_ROOT. This is the directory where the collectstatic management command will dump files, and should be served directly by your production webserver. Django never serves anything from here.
MEDIA_ROOT is for uploads, now, i.e. any time you have a FileField, ImageField, etc. on a model, the actual file will be put somewhere in here. It also should be directly served by your webserver in production. Don't put any of your static resources here.
Do put all of your static resources in your app's static directory. Each app's static directory will be served by Django in development under STATIC_URL. So, <project_root>/some_app/static/style.css will be available at /static/style.css through your browser. Because of this, it's usually a good idea to namespace your static directories, i.e. use <project_root>/some_app/static/some_app/style.css instead so that the URL becomes /static/some_app/style.css. That way your static files don't overwrite each other.
If you need project-wide static resources, create an entirely different directory in your project (I tend to use assets) and then add that to STATICFILES_DIRS like so:
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), 'assets'),
)