Hello and thanks for your help in advance. I realize this question has been asked and answered in other placed but none of those answers are working for me.
I am new to python and django and have inherited a small webapp. I have a dev environment working on my computer with mostly unchanged code, the only changes being to the database name and password to point to my local mySQL server.
However, when I run the app, everything works except for the static files. I'm getting 404s in the console when trying to retrieve static files and js methods in static are coming up undefined.
The BASE_PATH, STATIC_URL, STATIC_ROOT, STATICFILES_DIR, STATICFILES_FINDERS are all unchanged from the currently working production code, and as far as my beginner eyes can tell are configured correctly according to the documentation and the multiple answers to this question.
Is there something that could be different about what I have installed on my computer that would be causing this? Why else would it be different between production and my local copy? Is there something I have to run to get this working?
Some settings in settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'biogen.apps.BiogenConfig',
'msm.apps.MsmConfig',
'tracker.apps.TrackerConfig',
'accounts.apps.AccountsConfig',
'process_manager.apps.ProcessManagerConfig',
'process.apps.ProcessConfig',
'pfd.apps.PfdConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'djangobower',
'rest_framework',
'crispy_forms',
'django_summernote'
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIR = [
os.path.join(BASE_DIR, 'components/static'),
]
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'djangobower.finders.BowerFinder',
]
Included in the templates:
{% load static %}
Thanks again in advance...
Provide something like this:
Consider you have in your project root directory static_files as a source and static as a destination of your static files - you initially place and edit them in static_files (or any other you have):
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static_files'),
os.path.join(BASE_DIR, 'static_files/js'),
os.path.join(BASE_DIR, 'static_files/html'),)
STATIC_ROOT = os.path.join(BASE_DIR, 'static', )
STATIC_URL = '/static/'
Notice it's STATICFILES_DIRS, not STATICFILES_DIR
Then run
python manage.py collectstatic
to collect your static files from static_files to static
Turns out I needed to load all the static files from Bower. All these files are present on production but not on development for some reason!
Try running
python manage.py collectstatic
Related
I am using fieldsets for my django forms.
Everything works fine on local. I wanted to uploaded onto Heroku and started running into problem.
When running "python manage.py collectstatic", I am getting the following error:
The CSS file 'forms_fieldset\css\main.css' references a file which could not be found: forms_fieldset/img/sorting-icons.svg
The message is correct. The file forms_fieldset/img/sorting-icons.svg is not mentioned in main.css.
I suppose there is two questions:
How does it know a file does not exist, if it actually not mentioned
anywhere?
How and where can I add this file?
Below is my settings.py, just in case someone wants to look at it:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"crispy_forms",
'main.apps.MainConfig',
'register.apps.RegisterConfig',
'import_export',
'forms_fieldset',
]
...
STATIC_URL = 'static/'
#IMAGE STUFF#
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
#Staticfiles_storage to make it compatible with Heroku
SATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
#storing static files
VENV_PATH = os.path.dirname(BASE_DIR)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),)
I'm new to Django and i've seen a lot of people asking about this particular problem but i followed every instruction i could find and it still doesn't work.
My directorys look like this:
/Peperina
/Writing
/statics/writing
/css
/scss
/js
forms.js
/templates/writing
forms.html
my setings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
(...)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'writing.apps.WritingConfig',
]
(...)
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
STATIC_URL = '/statics/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'statics'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
My urls.py:
(...)
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
finaly my forms.html
(...)
{% load static %}
<script src="{% static 'writing\js\forms.js' %}"></script>
yet 404 keeps showing up
Try to change your STATIC_ROOT to os.path.join(BASE_DIR, 'statics') ?
I have had this same problem multiple times myself.
I'd first start by removing the "writing" directory, and move all folders up.
You won't need to change your settings.py file too much if you start by doing that.
Create a new directory, called "static_root" in the same level as your current "statics" folder and copy all the static files you've got in your statics folder over to there. Be sure to have two copies of each (one in "statics" and another in "static_root"). This will be explained shortly.
Your static file information in settings.py should now be changed to look like this:
STATIC_ROOT = os.path.join(BASE_DIR, 'statics')
STATIC_URL = '/statics/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static_root'),
)
The reason you need to have a separate static_root is because Django sometimes gets a bit funny about there being a root static folder and a normal static folder. More info can be found here.
I personally do not have STATICFILES_FINDERS in my settings.py, so test with removing that.
Maybe also try running Python manage.py collectstatic as this will collect the static files for you.
If none of this works, as you mention you are new to Django, I'd recommend following some tutorials from start to finish to see if you can get it to work.
E.g. start here if you haven't done already.
Well this turned up to be a pretty goofy solution but i changed the name of all my "statics" directorys to just "static" and then did the same thing in my settings and... it worked
So... thanks anyway
Update: looks like this is being cause by the django-heroku package and specifically the inherited whitenoise package, which in docs says your supposed to put
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
at the end of settings file, which I never did but it still enforces root being 'staticfiles' folder instead of assets folder
Original Post:
When I run python manage.py collectstatic it saves to a folder called staticfiles
I must have done something to make this happen, but I've searched for staticfiles and found no reference to it except 'django.contrib.staticfiles'.
Here is my settings.py:
INSTALLED_APPS = [
#some apps
'django.contrib.staticfiles',
#some more apps
'tz_detect',
]
# some more code
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
VENV_PATH = os.path.dirname(BASE_DIR)
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root')
Expected outcome was for when python manage.py collectstatic is run, that an assets folder would be created, but this never happens.
The staticfiles folder in addition to files from static folder also contains a tz_detect folder (from static assets from 3rd party package), an admin folder, and a staticfiles.json
middleware section of settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# some more middleware
'tz_detect.middleware.TimezoneMiddleware',
]
It appears that it isn't possible to change the name of your STATIC_ROOT using django_heroku, without monkey patching the package.
The line django_heroku.settings(locals()) takes all the local variables (ie STATIC_ROOT) and passes them into the settings function found at django_heroku/core.py.
If you take a look at line 89:
config['STATIC_ROOT'] = os.path.join(config['BASE_DIR'], 'staticfiles')
You will see that whatever value you set for STATIC_ROOT, the package will override it with staticfiles.
Note that the following may have unintended consequences, and you shouldn't do them.
Here are 2 monkey patch solutions:
change the value of STATIC_ROOT after you call django_heroku.settings(locals()):
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
modify django_heroku/core.py line 89: to the following:
if 'STATIC_ROOT' not in config:
config['STATIC_ROOT'] = os.path.join(config['BASE_DIR'], 'staticfiles')
this will prevent djano_heroku from overriding the STATIC_ROOT if you have already defined it.
Again, I don't recommend doing this because there might a good reason that Heroku forces you to use the name staticfiles, and this might cause your server to break, or worse, parts of your server might silently fail (which means debugging will be a nightmare).
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
I want to use static files to load my css with runserver command. The problem is that i tried all the solution i found here on stackoverflow and also in django docs, but it doesnt works at all... I dont know what can i do...
If i set
STATIC_URL = '/static/'
STATIC_ROOT = 'C:\Users\Max\Works\www\mysite\mysite\static'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
)
I thought it was enough... Am i missing something?
Can you tell me what is the best setting for have static files in develompent envirnoment?
Thanks in advice...
EDIT(1)
I already putted in my template {{ STATIC_URL }}css/dark-grey.css" and ofc the css is in C:\Users\Max\Works\www\mysite\mysite\static\css\dark-grey.css, i really can't get what is wrong...
Use / slashes and NOT \ slashes in the path, even for windows paths.
In your settings.py
DEBUG=True
As per the docs:
This view is automatically enabled by runserver (with a DEBUG setting
set to True).
Using the URL pattern is a way to force it, which I personally don't even have to do in my project as long as DEBUG=True. You would always have DEBUG on when you are developing, and when you switch to production you aren't even using the development server anyways, so you would be pointing your production server to the static location.
This is a snippet of my static settings from my settings.py. I do not manually have to add that static view URL
import os
DEBUG = True
PROJECT_ROOT = os.path.dirname( __file__ )
PROJECT_NAME = os.path.basename(PROJECT_ROOT)
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_ROOT, 'web/'),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.static',
...
...
)
You need to add url patterns:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
See the documentation here
You also need to run the following command to get the static files moved into the right place (and for Django to know they're there):
python manage.py collectstatic
Full documentation on static files in Django 1.3 is here:
https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/