I am unable to use CSS and JS files in my django project.
Folder structure:
mysite/
mysite/mysite/settings.py
mysite/mysite/templates/base.html
mysite/mysite/assets/css/...
settings.py
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = 'static'
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',...)
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
base.html
running python manage.py collectstatic returns:
"Your STATICFILES_DIRS setting is not a tuple or list; "
django.core.exceptions.ImproperlyConfigured: Your STATICFILES_DIRS setting is not a tuple or list; perhaps you forgot a trailing comma?
You never manually put anything STATIC_ROOT. It is only a dumping ground for collectstatic in production; it shouldn't even exist in development.
All of your static resources need to go in one of your apps' static directories, or if you need project-wide resources, you must create an entirely different directory for that is not the same as either MEDIA_ROOT or STATIC_ROOT and add it to STATICFILES_DIRS:
STATICFILES_DIRS = (
os.path.join(PROJECT_PATH, 'assets'),
)
You can call it whatever you want; I typically use "assets". Just don't name it "static", "media", "site_media", etc., just to avoid confusion.
Related
I would like to use django staticfiles, but unfortunately I can't get it to serve to images locally.
This is what I have done so far:
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'content.apps.ContentConfig',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
When I do a print(os.path.join(BASE_DIR, 'staticfiles')) I see the correct local path.
urls.py:
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
import content.views
urlpatterns = [
path('admin/', admin.site.urls),
path('', content.views.index, name='index'),
path('/about', content.views.about, name='about'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
templates:
{% load static %}
...
{% static "css/master.css" %}
resolves to
/static/css/master.css
[EDIT]
URL PATTERN looks like this
Using the URLconf defined in website.urls, Django tried these URL
patterns, in this order:
admin/
[name='index']
/about [name='about']
^static/(?P<path>.*)$
Opening a file directly ends up to a 404-django-page.
After that, I ran ./manage.py collectstatic successfully.
I am using the Django Dev server e.g. ./manage.py runserver...
I am maybe missing something, just need an additional pair of eyes. Thanks.
Solved it by removing
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
and replacing it with
STATICFILES_DIRS = (os.path.join(BASE_DIR, "staticfiles"),)
I cant figure out how to make Azure App Service use css for admin panel.
In settings.py I included these:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
But somehow css is still not working for the admin panel.
How can I fix this? As far as I know Oryx which works under Azure App Service should automatically run
python manage.py collectstatic
Any ideas?
EDIT:
Installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'licenses_api',
]
There are something to check might help:
Click F12 on your Admin page to check if it is the 404 Not Found error.
Check the static files exist in your azure web app or not. You could see it in https://{your-web-app}.scm.azurewebsites.net/wwwroot/ site.
Check if your file structure match with the settings.py. Any spell error would make the static file not found.
If your file exists well, you should check if you use them correctly in your code like this answer. Here is how he use:
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)
Firstly try to add these code lines to
settings.py
STATIC_URL = '/static/'
if DEBUG:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Then import these lines to the
urls.py
from django.conf.urls.static import static
from django.conf import settings
from django.conf.urls import url
from django.views.static import serve
Finaly you have to add these lines to urlpatterns in
urls.py
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
(If you have not already created a static file please make sure to create one before you try this)
It's worked severl times for me and hope this will work for you too 😊
Project name is exam. I place simple.css file in exam/static/css/. When I request http://127.0.0.1:8000/static/css/simple.css, it returns 404 error, saying 'css\simple.css' could not be found. The settings seem all right. In production environment the static requests are all right with nginx.
Related infomation:
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))).replace('\\','/')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [
],
'APP_DIRS': True,
},
]
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\','/')
STATIC_ROOT = os.path.join(BASE_DIR, "static").replace('\\','/')
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
)
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL , document_root = settings.MEDIA_ROOT )
Perhaps you're missing the STATICFILES_DIRS setting.
When in production, python manage.py collectstatic moves all static files inside STATIC_ROOT directory so nginx can look up here for them, however in dev mode, django needs to know where the static files are, and use STATICFILES_DIRS tuple for that.
If you have these files inside exam/static, your STATICFILES_DIRS should looks like:
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
If you are using ./manage runserver then you're missing STATICFILES_DIRS.
For nginx/gunicorn http://nginx.com/resources/admin-guide/serving-static-content/. Also Django White Noise
So ive been trying to setup a django settings module that will check the environment variable and load settings.
Heres what my settings module looks like
/templates
home.html
/settings
base.py
prod.py
dev.py
test.py
base.py
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = [
os.path.join(PROJECT_ROOT, "templates"),
]
urls.py
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
url(r"^$", direct_to_template, {'template' : 'home.html' }, name="home"),
)
When I had all of my settings in one file, this worked just fine, but since I split the files up I get the error:
TemplateDoesNotExist at /
home.html
Template-loader postmortem
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
/Users/Tulsa/Apps/tulsa-applications-co/tulsa/tulsa/settings/templates/home.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/django/contrib/auth/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/django/contrib/admindocs/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/grappelli/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/django/contrib/admin/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/pagination/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/djangosaml2/templates/home.html (File does not exist)
/Users/Tulsa/Apps/tulsa-applications-co/tulsa/tulsa/apps/profiles/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/debug_toolbar/templates/home.html (File does not exist)
Using loader django.template.loaders.eggs.Loader:
what am i missing here?
All answers above require of configuring TEMPLATE_DIRS or TEMPLATE_LOADERS, which is not necessary and correct. You just have to put YOUR application to the INSTALLED_APPS.
For example, if your application is in the MyMegaApp (where settigs.py resides), in other words you have a project structure like below
MyMegaApp
MyMegaApp
templates
index.html
settings.py
manage.py
Then you have to add your app like this
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'MyMegaApp'
)
After that your index.html template will be found in MyMegaApp/templates folder
The problem here is, in your settings, your PROJECT_ROOT evaluates to the directory which runs manage.py.
You may do this for TEMPLATE_DIRS settings
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
print PROJECT_ROOT
Now, append ../../ relative to the PROJECT_ROOT. Something like this:
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../'))
TEMPLATE_DIRS = [
os.path.join(PROJECT_ROOT, "templates"),
]
Change your PROJECT_ROOT to:
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
And make sure your TEMPLATE_LOADERS variable is set properly.
Explanation:
abspath gives you the full path of the base.py, i.e., /home/some-path/project-folder/settings/base.py
Therefore, first dirname gives you the dir path name of the given path (obtained above), i.e., /home/some-path/project-folder/settings/
And then, the second dirname gives you the dir path name of the given path (obtained above), i.e., /home/some-path/project-folder/
So, now when you join this path to templates, everything starts working fine.
For more refer python docs.
can you test as below?
i think your code would set PROJECT_ROOT as '/some/path/to/settings'
from os.path import dirname, abspath, normpath, join
PROJECT_ROOT = dirname(dirname(abspath(__file__)))
TEMPLATE_DIRS = (
normpath(join(PROJECT_ROOT, 'templates')),
)
Include this in settings
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(SITE_ROOT, 'appname/templates'),
)
Add this to urls.py
from django.conf.urls.defaults import *
from django.views.generic.simple.direct_to_template import direct_to_template
from appname.views import *
call url by
urlpatterns = patterns('django.views.generic.simple',
(r'^foo/$', 'direct_to_template', {'template': 'foo_index.html'}),
(r'^foo/(?P<id>\d+)/$', 'direct_to_template', {'template': 'foo_detail.html'}),
)
I'm using django-nonrel on google app engine.
I've got this problem when visiting http://localhost:8080/album
Could not import myapp.views. Error was: No module named myapp.views
my urls:
urlpatterns = patterns('',
('^_ah/warmup$', 'djangoappengine.views.warmup'),
('^$', 'django.views.generic.simple.direct_to_template', {'template': 'home.html'}),
(r'^album/$', 'myapp.views.view_albums'),
(r'^admin/', include(admin.site.urls)),
)
my views:
def view_albums(request):
return direct_to_template(request, 'album.html', locals())
Part of Settings:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
# 'django.contrib.sites',
'djangotoolbox',
# djangoappengine should come last, so it can override a few manage.py commands
'djangoappengine',
)
PROJECT_DIR = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media/')
ADMIN_MEDIA_PREFIX = '/media/admin/'
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)
ROOT_URLCONF = 'urls'
I'm not using django's site framework, the app structure is
myapp
-\dbindexer
-\django
-\djangoappengine
-\djangotoolbox
-\media
-\templates
-__init__.py
-app.yaml
-views.py
-urls.py
-settings.py
-models.py
-manage.py
-cron.yaml
-dbindexes.py
...
I think you are using
from myapp.views import * in urlconf
please try
-- in urlconf
from views import *