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
Related
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).
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
I know a million people have asked this, and I've read and read but still cannot get this to work (I think that says something about the documentation cough cough).
ONE. CSS:
Here are my settings:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'))
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static")
STATIC_ROOT = '/static/'
STATIC_URL = '/static/'
also relevant:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'blog',
)
My templates are serving up just fine, while my css is not. its located in static/originaltheme.css
I've tried both:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}originaltheme.css">
and
<link rel="stylesheet" type="text/css" href="/static/originaltheme.css">
TWO. Also, is there a way to get hardcoded urls to display? for example, lets say the content of a blog post has a hardcoded url to /static/img1.jpg, how can I do that? All of the documention points to {{ static_url }}, but im guessing that that wont get evaluated when returned from a text field of a database...
is there something to do with my urls?
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'nickswebsite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', 'blog.views.index'),
url(r'^blog/view/(?P<slug>[^\.]+)',
'blog.views.view_post',
name='view_blog_post'),
url(r'^blog/category/(?P<slug>[^\.]+)',
'blog.views.view_category',
name='view_blog_category'),
url(r'^admin/', include(admin.site.urls)),
)
EDIT:
I tried doing this is in the urls:
urlpatterns = patterns('',
url(r'^$', 'blog.views.index'),
url(r'^blog/view/(?P<slug>[^\.]+)',
'blog.views.view_post',
name='view_blog_post'),
url(r'^blog/category/(?P<slug>[^\.]+)',
'blog.views.view_category',
name='view_blog_category'),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=setting.STATIC_ROOT)
urlpatterns += staticfiles_urlpatterns()
but im getting a "settings" undefined error. I tried to import settings and im still getting an error.
Edit
Okay, the documentation for serving static off development server is HORRIBLE. Whoever wrote it should really rewrite it. This guy is the only person in the entire world who seems to explain this clearly: http://agiliq.com/blog/2013/03/serving-static-files-in-django/#servee
You DO need these in the settings.py (why arent they included in the initial installaion??? what genius...):
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
You do NOT need these:
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static")
STATIC_ROOT = '/static/'
You do NOT need:
manage.py collectstatic
http://agiliq.com/blog/2013/03/serving-static-files-in-django/#servee:
Points to be noted
We did not make any changes to any of the static settings provided by Django to us. We left the static settings as they were in default settings.py provided by Django.
You don't need any change in your urls.py for serving your static files in development. You don't need to add staticfiles_urlpatterns(). Many a times, I got confused with this.
You do not need python manage.py collectstatic for serving static files in development.
I also fought against this particular problem. And finally came up with this blog post
Actually you don't need collectstatic , STATICFILES_FINDER and django.contrib.staticfiles. They are all related. Read the blog post
I added these lines to the bottom of my url.py:
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
And this in my settings.py:
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Did you use:
./manage.py collectstatic
Also your STATIC_ROOT should be absolute path to the directory static files should be collected to:
STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, "static"))
This is what I did for Django 2.0 using the above answers. So you'll want a system that makes deployment easy.
settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Serve Static in Development
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATICFILES_DIRS = [os.path.join(BASE_DIR, "appName/static/appName")]
# Serve static in production
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Then made a directory ~/documentRoot/appName/static/appName/ and copied my png into it. Then in my template:
<head>
<bootstrap,jquery,etc...>
{% load staticfiles %}
</head>
<body>
<img class="mb-4" src="{% static "myImage.png" %}" alt="" width="72" height="72">
</body>
Then when you want to deploy you just run collectstatic and they'll be served in one spot. Each time you add an app, add to that list of static dirs.
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'),
)
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/