I am trying to make Django's development server to serve static files that have been collected by the python manage.py collectstatic command. For now I failed.
My Django settings file declares this:
STATIC_ROOT = os.path.join(WWW_PATH, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(ROOT_PATH, 'front', 'public'),
os.path.join(ROOT_PATH, 'front', 'dist')
)
This makes the collectstatic command copying files from os.path.join(ROOT_PATH, 'front', 'public') and os.path.join(ROOT_PATH, 'front', 'dist') to STATIC_ROOT, and it works perfectly.
I was assuming that it would also tell Django to look for static files into the STATIC_ROOT directory, I was wrong. Even if the STATIC_ROOT directory does not exists, Django is able to serve the static files. But if the os.path.join(ROOT_PATH, 'front') is missing, Django no more serve the static files.
This shows that Django continues to serve static files from the sources directories and not from STATIC_ROOT.
So I would like to know if there is a way to instruct Django's development server to serve static files from STATIC_ROOT. Any hint?
EDIT:
After #e4c5 's answer I modified my root urls.py like this:
static_patterns = [
url(r'^$', TemplateView.as_view(template_name='index.html'))
]
urlpatterns = [
url(r'^', include(static_patterns)),
url(r'^admin/', admin.site.urls),
url(r'^api/resa/', include('reservation.urls')),
url(r'^api/auth/', include('authentication.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
unfortunately, it does not have the expected result and Django does not find static files in STATIC_ROOT, I doubt that it actually looks for static files in STATIC_ROOT.
here is what I can see in the console when accessing to the index page:
[04/Jun/2017 16:18:05] "GET / HTTP/1.1" 200 1411
[04/Jun/2017 16:18:05] "GET /static/style/index.css HTTP/1.1" 404 1759
[04/Jun/2017 16:18:05] "GET /static/style/react-datetime.css HTTP/1.1" 404 1786
[04/Jun/2017 16:18:05] "GET /static/style/react-big-calendar.css HTTP/1.1" 404 1798
[04/Jun/2017 16:18:05] "GET /static/script/bundle.js HTTP/1.1" 404 1762
here are the content of the settings variables:
>>> from django.conf import settings
>>> settings.WWW_PATH
'/home/tryph/PycharmProjects/resa/www'
>>> settings.STATIC_ROOT
'/home/tryph/PycharmProjects/resa/www/static'
>>> settings.STATIC_URL
'/static/'
here is the content of the WWW_PATH directory:
/home/tryph/PycharmProjects/resa/www
└── static
├── admin
│ [...]
├── favicon.ico
├── index.html
├── rest_framework
│ [...]
├── script
│ └── bundle.js
└── style
├── index.css
├── react-big-calendar.css
└── react-datetime.css
This is done using static.serve
There may be files other than your project’s static assets that, for
convenience, you’d like to have Django serve for you in local
development. The serve() view can be used to serve any directory you
give it. (This view is not hardened for production use and should be
used only as a development aid; you should serve these files in
production using a real front-end web server
Change your urls.py like this:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Related
Got my Django project on a Azure webapp, but when I call on SSH terminal:
Python manage.py collectstatic
It says 252 files copied but my static files are not visible on my templates and static folder in wwwroot its empty...Here's my wwwroot structure:
wwwroot
|---Myproject
|---manage.py
|---oryx-manifest.toml
|---hostingstart.html
|---static //With all my static files
├── myapp
│ ├── migrations
│ ├── __pycache__
│ ├── static
| | |---Images
| | | |--myimage.png
| | | |--myimage2.png
│ └── templates
And this is my settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('myapp', os.path.join(BASE_DIR, 'myapp', 'static')),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Any idea why or what am I doing wrong ?, does Azure collect different ?
EDIT> When I go to my website my images don´t show...Im calling them like this on template:
{% load static %}
<img src="{% static 'Images/myimage.png' %}" /><br>
EDIT 2 /////
In wwwroot creates indeed a folder with all my statics, but when I load my template they don´t show, in wen console I get this error for myimage.png and myimage2.png :
Failed to load resource: the server responded with a status of 404 (Not Found)
Found it !!
Just had to add this: + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to url patterns like this:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('myapp/', include('myapp.urls')),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
And it did the trick, hope it helps to anyone else!!
Django does not serve static files in production mode.
The only time it serves static files is when you turn DEBUG = True which is in development mode and this is not recommended in a production setting.
Django recommends to serve static files via CND or any other webserver. However if your website is minimal and does not get high volume traffic you can serve your static files using Django whitenoise and here is how you do it.
The below solution works on python 3.7 and Django 3.2
Step 1: Install whitenoise package
pip install whitenoise
Step 2: Ensure your BASE_DIR looks like the below
BASE_DIR = Path(__file__).resolve().parent.parent
Step 3: Add these to your settings.py. If you get any errors try commenting out STATICFILES_STORAGE and check
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Step 4: WhiteNoise middleware should be placed directly after the Django SecurityMiddleware (if you are using it) and before all other middleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
Step 5: Ensure this is how you reference static files in your templates(also check if you have {% load static %} mentioned in your template
<link rel="stylesheet" type="text/css" href="{% static 'appname/styles.css' %}">
Step 6: Run collect static
python manage.py collectstatic
Step 7: Turn DEBUG = False and run the server to verify it works.
Some additional resources to read further:
whitenoise
Django on Azure - beyond "hello world"
Few points to note:
Below line will change
STATIC_ROOT = (os.path.join(BASE_DIR, 'Myproject/static_files/'))
to
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
You are using pointing to completely different folder here. Hence always empty You need the collectstatic command to copy files to
Project > static directory
Below remove the line os.path.join(BASE_DIR, 'static/')...
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/'), #Not Required since you already mentioned it in STATIC_URL
('myapp', os.path.join(BASE_DIR, 'myapp', 'static')),
)
Reason:
STATIC_ROOT is the folder where static files will be stored after
using manage.py collectstatic
The absolute path to the directory where collectstatic will collect
static files for deployment.
If the staticfiles contrib app is enabled (default) the collectstatic management command will collect static files into this
directory. See the howto on managing static files for more details
about usage.
STATICFILES_DIRS is the list of folders where Django will search for
additional static files aside from the static folder of each app
installed.
This setting defines the additional locations the staticfiles app will
traverse if the FileSystemFinder finder is enabled, e.g. if you use
the collectstatic or findstatic management command or use the static
file serving view.
If issue still persists check your static file directory in apache mod_wsgi config file in the server if it is configured properly.
Check this link for help on that >> https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/modwsgi/
Cheers!!!
I would recommend checking out Whitenoise for serving your static files with Django. I haven't had an issue serving them since integrating Whitenoise. Try swapping it out with your current static file finders setup.
http://whitenoise.evans.io/en/stable/django.html
I have a problem with static files in my Django application.
I create a simple blog app with Django REST Framework and Angular 6. It's working fine in my local development environment, but I have a problem with deploying it to production. The thing is, the app is loading (I know that because the root route is a redirection to /app and I am being redirected correctly) but there are no static files loaded.
Here is part of my configuration related to the static files:
STATIC_URL = '/static/'
BASE_DIR = os.path.join(
os.path.dirname(os.path.dirname(__file__)), '..', '..', '..'
)
STATIC_ROOT = os.path.join(BASE_DIR, 'app', 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'frontend'),
]
INSTALLED_APPS = [
...
'django.contrib.staticfiles'
...
]
The paths are correct, I triple-checked them to be sure. And here are routes configured in Django application:
urlpatterns = [
url('^api/', include(api_patterns)),
url('^admin/', admin.site.urls),
url('^app/', serve, kwargs={'path': 'index.html'}),
url('^$', HomepageView.as_view(), name='homepage-redirection'),
]
I am able to run manage.py collectstatic without any errors and all static files are correctly copied to the static directory. Static files for admin application are not loaded correctly as well. Here is a rough structure of directories in my project:
├── app
│ └── (python code here)
├── frontend
│ └── (angular code here)
├── media
│ └── (empty for now)
└── static
└── (static files for Django)
The application server is nginx with Phusion Passenger (this was configured by my the company I rent the server from). I don't really know what else I can add here. Does anyone have any idea what can be wrong here? Maybe some hint would be the fact that the API endpoints are not accessible. I have access to admin application, but not to API (both configured in the same urls file).
Okay, all. I know this is a question that many people have solved in various cases, but I cannot for the life of me get my Django 1.9 development server to serve static content on my local computer. Static files worked fine pre-deployment, and are totally fine on my deployment server, but now in my test environment (local computer with runserver going) everything is broken, and I really need to be able to test stylesheets in a dev environment.
I have tried all of these solutions and more, followed the documentation guide, used collectstatic again in the development repo... nothing has worked, and I am at my wits' end.
Currently, I have DEBUG = True, and the following setup:
Folder Hierarchy
project/
manage.py
(&c)
app/
urls.py
models.py
(&c)
project/
settings.py
urls.py
(&c)
static/
styles/
images/
(&c)
settings.py Static Files Settings
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(STATIC_ROOT, 'styles/'),
os.path.join(STATIC_ROOT, 'js/'),
os.path.join(STATIC_ROOT, 'audio/'),
os.path.join(STATIC_ROOT, 'images/'),
os.path.join(STATIC_ROOT, 'admin/'),
os.path.join(STATIC_ROOT, 'documents/'),
)
urls.py URL Patterns
from django.conf.urls import include, url, patterns
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
# ... project url patterns blah blah ...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':settings.STATIC_ROOT, 'show_indexes': True}))
I also have {% load staticfiles %} in my templates along with the appropriate {% static %} calls (ex: {% static 'styles/main.css' %}).
For reference, the command line gives me the following when I load the page:
"GET /static/styles/main.css HTTP/1.1" 404 1759
If anyone knows of a fix I have missed that might even remotely have a snowball's chance of working, please let me know. It's driving me bonkers not being able to test properly.
EDIT: As suggested, I have updated to Django 1.11 on my local machine, with no changes to the current issue.
I'm not able to test it out, but maybe try changing this:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
to this:
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
By the way, version 1.9 is unsupported and also a security risk. You'd probably want to upgrade to another version.
Can you try to create the STATIC_ROOT var with the absolute path and check if it works?
Maybe the construction of that var is not OK.
You could also check the STATIC_ROOT var through
python manage.py shell
and see if it correctly fits your path.
I'm using heroku to host my Django(1.6) app (called 'Zen'). The problem is static files aren't showing. In other words, there's no CSS and no JS in my app because it doesn't found those files. I looked to other questions here and I configured my app as below:
Settings.py:
##### Static asset configuration #####
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
urls.py:
from django.conf.urls.static import static
from zen import settings
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zen.settings")
application = Cling(get_wsgi_application())
Apparently, after pushing my app with git push heroku master all is working great:
-----> Preparing static assets
Running collectstatic...
69 static files copied to '/app/staticfiles'.
But as you can see there is no CSS in my app (http://obscure-reef-8874.herokuapp.com/). I looked to my app's log and mostly css and js files are in 404 status... I tried everything, can you help me?
EDIT:
I didn't find the bug, I recreated an app and it worked, simple.
Set
STATIC_ROOT = 'static'
try
May be caused by different STATIC_ROOT and STATICFILES_DIRS
The problem is not with your static file serving: that is fine, as you can see if you go to the admin application: http://obscure-reef-8874.herokuapp.com/admin/. Files under /static/admin/ are being served with no problem.
Without seeing the structure of your application and the way you are outputting the static links in your template it's hard to help, I guess that your files are inside a subdirectory of /static/, so you'll need to reference that subdirectory in the links to the assets in your template.
Note that you should remove the additional static URL patterns from your urls.py. They do not work when DEBUG is False. Your files are served by Cling, which is external to Django.
I'm stuck due to an evergreen issue, static files not served. Conversely the files placed in the MEDIA_ROOT subtree get served correctly under MEDIA_URL.
Stripped settings.py:
DEBUG = True
STATIC_URL = '/static/'
STATIC_ROOT = '/home/foo/devel/static'
MEDIA_URL = '/media/'
MEDIA_ROOT = '/home/foo/devel/media'
# the following is deprecated but is it seems grappelly requires it
ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/"
STATIC_FILES = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
To create the project I did:
$ cd /home/foo/devel/
$ virtualenv testdrive
$ . bin/activate; pip install django; cd testdrive
$ django-admin.py fbtest
and got this directory tree (stripped):
. <-- /home/foo/devel/
├── bin
├── fbtest
│ └── fbtest
│ ├── media
│ │ └── foo.jpg
│ ├── static
│ └────── foo.jpg
├── include
└── lib
Files under STATIC_URL should be served automatically by Django staticfiles (not in my case), while other files have to be handled manually. So I appended these lines to urls.py:
import settings
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip("/"),
'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
Accessing http://host/media/filebrowser/foo.jpg works, while http://host/static/foo.jpg gives error 404. Why?
Files under STATIC_URL should be served automatically by Django staticfiles (not in my case), while other files have to be handled manually.
That's incorrect. Django never serves STATIC_ROOT ever -- not even in development. What it does do is make files in each app's "static" directory and files in any directory specified in STATICFILES_DIRS available at STATIC_URL. You don't actually manually put anything in STATIC_ROOT ever; in fact, in development, you shouldn't even have the directory there. Put simply, STATIC_ROOT is only a dumping ground for your static files in production when you run the collectstatic management command.
In development, all static files should go into someapp/static, where "someapp" is the app they apply to. In the case that the files apply to the project as a whole, a global CSS file for example, you need to create an entirely different directory (i.e. not the same as STATIC_ROOT or MEDIA_ROOT) and then add that directory to STATICFILES_DIRS. For example, I normally call mine "assets", so:
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), 'assets'),
)
It was a silly error. I forgot to add fbtest to INSTALLED_APPS, so the static file machinery didn't manage static files for this app.
This problem is realy evergreen...
Some hints:
TEMPLATE_CONTEXT_PROCESSORS = (
# ...
'django.core.context_processors.static',
# ...
)
INSTALLED_APPS = (
# ...
'django.contrib.staticfiles',
# ...
)
Did you use? django-admin-collectstatic command?
Can you help add show_indexes=True in url settings?
Some symbolic link?
Run app with --adminmedia=../grappelli/static/grappelli arg.?
My settings for django 1.4 (no grappelli):
urls.py
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^%s(?P<path>.*)$' % settings.STATIC_URL.lstrip('/'), 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT, "show_indexes": True}),
url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip('/'), 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, "show_indexes": True}),
) + urlpatterns
settings.py
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
TEMPLATE_CONTEXT_PROCESSORS = (
# ...
'django.core.context_processors.static',
# ...
)
INSTALLED_APPS = (
# ...
# 'django.contrib.staticfiles',
# ...
)