Problem
I'm building a django web app. I can't get to display a static file (icon) in an html template when I run my app locally (ubuntu 20.04, python 3.8.5, django 3.1.4).
I DO NOT HAVE THIS ISSUE WHEN DEPLOYING ON HEROKU CLOUD, only on my localhost.
When loading up the webpabe on my localhost, I can see "GET /static/icons/graph-up.svg HTTP/1.1" 404 1781 in the Django wsgi console.
My project tree:
django-project
|_ ...
|_ static
|_ icons
|_ graph-up.svg
index.html
{% load static %}
<img src="{% static 'icons/graph-up.svg' %}" />
settings.py
[...]
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# I've tried with and without whitenoise, doesnt seem to change anything
MIDDLEWARE = [
# 'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
[...]
urls.py
urlpatterns = [
path('', views.home, name='index'),
...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I've followed the instructions from https://docs.djangoproject.com/en/3.1/howto/static-files/
Any ideas or suggestions welcome!
What I've tried locally so far
Without success (icon gets 404 error)
python manage.py runserver (to run with the wsgi from django)
gunicorn my_app.wsgi
heroku local (to simulate the heroku web server which is gunicorn locally)
python manage.py runserver --insecure (from Django Static files 404)
load the app locally with/without the whitenoise.middleware.WhiteNoiseMiddleware line in MIDDLEWARE after django.middleware.security.SecurityMiddleware
With partial success
Following an answer from Django Static files 404:
I replaced:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
with:
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join('static'), )
I reloaded the wsgi and voila. The icon shows up.
However when I revert back to the original
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Just to see what happens, the icon still shows up.
Conclusion
I'm not sure this is the right thing to do but it seems to be working fine. Here's how I workaround the issue.
In my settings.py (for heroku):
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
In my settings_dev.py (for localhost):
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join('static'), )
I don't know exactly what the problem is but to fix it you can use Whitenoise module, used to serve staticfiles
for Reference: https://youtu.be/kBwhtEIXGII
for in detail info.: http://whitenoise.evans.io/en/stable/
I have django admin panel working on a vps ( Windows Server 2012 ) , Why it is not showing any css styles or boostrap ? it is showing just html and nothing else .
https://docs.djangoproject.com/en/2.1/howto/static-files/
During development, if you use django.contrib.staticfiles, this will
be done automatically by runserver when DEBUG is set to True (see
django.contrib.staticfiles.views.serve()).
So when you change DEBUG=False to move out of development, Django runserver will no longer automatically serve static files.
Here is an alternate method using http://whitenoise.evans.io/en/stable/django.html
whitenoise for serving staticfiles in deployment
1) pip install whitenoise
2) Add 'whitenoise' to installed_apps
3) Give STATIC_ROOT to a folder like:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
4) Run to collect staticfiles in STATIC_ROOT directory
python manage.py collectstatic
5)Add STATICFILES_STORAGE(optional)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
6) Add in middleware before everything except 'django.middleware.security.SecurityMiddleware', like:
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
7)Change to DEBUG=False in settings.py
More details here http://whitenoise.evans.io/en/stable/django.html
I've seen lots of different posts regarding the Django static file issues. Unfortunately, none of them seem to help me. My django admin css is fine, however static files are giving my a 404 error. Here is a description of what my problem:
In settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = '/Users/me/develop/ember/myproj/static/'
In urls.py:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
My project directory:
> static
> myproj
> app
> templates
> ember.hbs
> img
> test.jpg
Inside my ember.hbs I reference the test.jpg, but I get a 404 error. It's weird because I can actually pull up the image using:
file:///Users/me/develop/ember/proj/static/myproj/img/test.jpg
I have no idea what to do to fix this, I've tried using the STATICFILES_DIRS method mentioned here: https://docs.djangoproject.com/en/1.8/howto/static-files/
but nothing seems to be working.
Thanks in advance!
More information: Django 1.8 and Ember-CLI.
I'm hosting the ember project within the static dir.
I'm running python manage.py runserver and running django on port 8000 at the same time as running ember s and running the application on port 4200. I'm using CORS-headers (https://github.com/ottoyiu/django-cors-headers/) to allow cross-site calls on development.
Static files will be discovered in "apps" that you create (found in INSTALLED_APPS) or in additional directories that you specify in STATICFILES_DIRS.
Let's say I did:
django-admin.py startproject myproject
And then:
cd myproject
./manage.py startapp myapp
mkdir myapp/static
mkdir myproject/static
Would give you a directory structure that looks something like
/Users/me/develop/myproject/
> myapp/
> migrations/
> static/
> __init__.py
> admin.py
> models.py
> tests.py
> views.py
> myproject/
> static/
> __init__.py
> settings.py
> urls.py
> wsgi.py
> manage.py
And then in settings.py you add "myapp" to INSTALLED_APPS.
In this structure, myapp/static/ files will be automatically discovered by Django because it is an installed app with a static directory. However, myproject/static/ files will NOT be discovered automatically because "myproject" is not in INSTALLED_APPS (and it shouldn't be).
This is because of the default STATICFILES_FINDERS setting, which is:
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.FileSystemFinder',
]
The first finder, AppDirectoriesFinder, scans the directories of all of your INSTALLED_APPS, and discovers any "static" folders they might contain.
The second finder, FileSystemFinder, scans extra directories that you specify in STATICFILES_DIRS, which is an empty list by default.
So if you want those files in /Users/me/develop/myproject/myproject/static/ to be discovered (as you probably do), you can add this to your settings.py:
from os import pardir
from os.path import abspath, dirname, join
# Get the root directory of our project
BASE_DIR = abspath(join(dirname(__file__), pardir))
# Add our project static folder for discovery
STATICFILES_DIRS = (
# /Users/me/develop/myproject/myproject/static/
join(BASE_DIR, 'myproject', 'static'),
)
Now, all of this is separate from STATIC_ROOT, which is a place where all static files are copied when you run ./manage.py collectstatic. For projects just starting out, this is usually in the project root folder: /Users/develop/me/myproject/static/
So we would add, in settings.py:
# /Users/me/develop/myproject/static/
STATIC_ROOT = join(BASE_DIR, 'static')
But this is only really used in production—it's a way to compile all of your static assets into a single spot, and then point /static/ at it with your server (e.g. NGINX).
During development, you can skip collectstatic altogether, and have Django discover and serve your static assets on the fly. Django provides a "serve" view to do this in django.contrib.staticfiles.views.serve.
Try this in your urls.py:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.views import serve
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
urlpatterns += [
url(r'^static/(?P<path>.*)$', serve),
]
In your example, you are asking Django to serve files from STATIC_ROOT, which is also fine, but requires you to run ./manage.py collectstatic first, and every time your static assets change—which can be a hassle.
Ember and Django really shouldn't live in the same project. They are completely different frameworks with different tooling.
Think of your Django project as the backend application that serves an API. Think of your Ember project as one of possibly many clients that will consume your API. Others might include mobile applications, partner services, and so on.
When I start a new project that is going to use Django and Ember, I start a Django project called "myproject":
django-admin.py startproject myproject
And separately, an Ember project called "myproject-web":
ember new myproject-web
In development, I'll have two tabs open in Terminal.
First tab:
cd myproject
./manage.py runserver
Second tab:
cd myproject-web
ember serve
In production, I'll have two different servers, one at app.myproject.com that serves the Django application, and another one at myproject.com that serves the Ember application.
Later on, I might start a Swift project in a repository called "myproject-ios", and a Java project called "myproject-android". You get the idea.
In order to serve the static files into your django project you just need to add these lines to your `settings.py
STATIC_URL = '/static/'
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
STATIC_PATH,
)
and then in the main stucture of your project dictory needs to be like
>Project_dir
>App_dir
>static_dir
>templates
>manage.py
place your css, js, and other static contents into your static_dir
My project runs fine on the local sever but during deployment on Heroku, I get the following error
Collectstatic configuration error. To debug, run: $ heroku run python manage.py collectstatic --noinput
I understand this is due to STATIC_ROOT settings in settings.py, but I can't seem to point to the location of the static files properly.
This is my folder structure.
C:/
/Users
/Mac
/denv
/musicpro
/musicpro
/featureapp
/static
/featureapp
/css
/img
/js
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = 'musicpro/featureapp/static/featureapp/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static")
)
I'm getting 404 for static files when DEBUG=False in my settings. The file is served fine when DEBUG=True.
I'm looking at the docs and all my configs seem OK to me.
# my_settings.py
STATIC_ROOT = os.path.join(PROJECT_PATH, 'static')
STATIC_URL = '/static/`
then I run collectstatic --settings=my_settings, and ls static to confirm it has collected the files. It has:
ls ls static/css/core.css
# (its there).
But when we request "localhost:8000/static/css/core.css" we get 404.
Note running python manage.py findstatic css/core.css --settings=my_settings fails to find the file. When I do DEBUG=True and run findstatic it finds the file, but in the sub app's static dir, not the collected directory (STATIC_ROOT).
Note I have:
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
and "staticfiles" is in my INSTALLED_APPS.
Django 1.6
As you have specified DEBUG = FALSE in settings, its now left on HTTP server like nginx or apache to serve the static files. You need to configure your webserver to serve static files. An example for apache can be found here.