I have the following Django project layout:
project_folder/
app_folder/
static/
folder1/
file1
templates/
...
compressor -> (symlink to django_compressor app with my modifications)
__init__.py
manage.py
settings.py
urls.py
From the templatetag specificed in my fork of django_compressor I'm calling a class that does the following:
class StorageMixin(object):
from django import VERSION as DJANGO_VERSION
if DJANGO_VERSION[:2] >= (1, 3):
from django.contrib.staticfiles.finders import find as _django_find
def _find_file_path(self, path):
return self._django_find(path)
else:
def _find_file_path(self, path):
static_roots = getattr(settings, 'STATIC_ROOTS', []) + [settings.COMPRESS_ROOT]
for root in static_roots:
filename = os.path.join(root, basename)
if os.path.exists(filename):
return filename
return None
So, if django is of the new version, it tries to use staticfiles finders, otherwise mimics its basic finder through the STATIC_ROOTS config variable.
Finally, the question: given the folders layout above, I pass "folder1/file1" to finders.find method, and I have the following settings:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'compressor',
'app_folder',
)
and
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
and I get None from the find call.
Any ideas?
UPD. More strange details: I ran
python manage.py shell
and did
from django.contrib.staticfiles.finders import find
find("folder1/file1")
And it gave me the correct result...
The answer was: import the whole module, not only the find method
I am using the static files with my new site and it took a while to get set up. Do you have something like this in your settings.py?
Also check out:
Django staticfiles app help
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/static/"
STATICFILES_ROOT = '/path/to/my/site/static/'
STATIC_ROOT = STATICFILES_ROOT
# URL that handles the static files served from STATICFILES_ROOT.
# Example: "http://static.lawrence.com/", "http://example.com/static/"
STATICFILES_URL = '/static/'
STATIC_URL = STATICFILES_URL
# URL prefix for admin media -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# A list of locations of additional static files
STATICFILES_DIRS = (
("game", BASE_DIR + "/game/media"),
("sitemedia", BASE_DIR + "/templates/media/"),
)
STATIC_DIRS = STATICFILES_DIRS
# 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',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
STATIC_FINDERS= STATICFILES_FINDERS
Related
I have a django app. Here is my directory structure.
.
+--media
+--index.html
+--static
+--extjs
+--<extjs files>
+--updater
+--app
+--images
+--ux
+--app.js
+--index.html
+--index.html
+--templates
+--<template files>
+--uapp
+--__init__.py
+--models.py
+-- <etc>
+--manage.py
+--settings.py
+--urls.py
here is my settings.py
import os
# Django settings for uproject project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#domain.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'updates', # Or path to database file if using sqlite3.
'USER': '<user>', # Not used with sqlite3.
'PASSWORD': '<password>', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Los_Angeles'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Path to project installation.
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
#MEDIA_ROOT = os.path.join(SITE_ROOT, 'static')
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/updater/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = "/static/"
# Additional locations of static files
STATICFILES_DIRS = (
#os.path.join(SITE_ROOT, 'static'),
# 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.
)
# 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',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'hnu51442$##gdsvx5v!61w^4-vjevy8xm6tqb56#bc216!nw-nl-%'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'urls'
# WSGI_APPLICATION = 'wsgi.application'
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, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'haystack',
'uapp',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
},
}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
LOGIN_URL = '/updater/uapp/login/'
LOGOUT_URL = '/updater/uapp/logout/'
LOGIN_REDIRECT_URL = '/updater/media/updater/'
CACHE_BACKEND = 'db://listclient_cache'
When I go to localhost:8000/static/updater/ I get Directory Indexes not allowed here error.
Any idea? I think there is some error in the way static files are being served. I am using extjs by the way.
I am expecting the index.html in static/updater/ directory to show up. Does it happen by default?
It seems that for some reason Django doesn't want to serve the directory listing of /static/updater/. Because static updater is a directory, not a file, try doing /static/updater/index.html or just /static/index.html and see if either are served. If they are not served, it may be an issue with your static files setup. If so, then I am not sure if it's just Django refusing to serve directory indexes within static folders or something else.
(This feels like it should be a comment, but I don't have enough rep to comment.)
Your STATICFILES_DIRS is empty - the dev server will serve from here.
You must edit your urls.py and add these lines to it then go to django.views.static.serve and change show_indexes argument to True.
Addition of urls.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
#import this at top
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root':"path\to\your\static\folder"}),
#add this to urlpatterns variable
urlpatterns += staticfiles_urlpatterns()
#add this in last line of urls.py
Now you are finished and django shows indexes
if you want to change the html view of it you must follow instructions in django.views.static.serve and add your favourite html file to static/directory_index.html
In addition to henrikstroem's answer:
You should have a look at the official documentation on STATIC_ROOT and STATICFILES_DIRS.
Basically, STATIC_ROOT is the location where the collectstatic command will collect all the static files to, and STATICFILES_DIRS is the location (or are the locations) where that command will look for static files.
My development setup looks like this:
project_root
+ apps
+ project
__init__.py
settings.py
urls.py
wsgi.py
+ run
dev.sqlite3
+ media
+ static
+ static
+ templates
I point STATIC_ROOT to project_root/run/static and include project_root/static in STATICFILES_DIRS.
As you can see, I store my static assets in project_root/static and they get served.
During development (meaning: while using the runserver command), your static assets will be served directly from their location, in my case project_root/static. When deploying, you will collect your static assets to STATIC_ROOT.
This can be a folder in your project (as my project_root/run/static or even a directory in a totally other environment, you may even copy them over to a CDN [Content Delivery Network]).
Personally, I like deploying with Apache. I will setup one virtualenv to handle the Django parts. Static assets are served by another virtualenv which totally bypasses all dynamic handling and simply serves static files. You could even use another server, like nginx, for this task.
In shameless self-advertising, you can fetch my project skeleton here.
I can't seem to get django static files working when I visit /static/accept.png it returns a 404. I have the file in project_folder/static
My installed apps has static files included
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
and this is what setting up the static files looks like
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_PATH = os.path.join(BASE_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_PATH = os.path.join(PROJECT_PATH,'static')
STATIC_URL = '/static/' # You may find this is already defined as such.
STATICFILES_DIRS = (
PROJECT_PATH + STATIC_URL,
)
Also I am trying to get this working locally i'm not worried about getting it to work in production yet.
You PROJECT_PATH is wrong. It points to one level up of the real project path.
Try these settings:
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
STATIC_PATH,
)
Don't get confused with PROJECT_PATH and BASE_DIR, if you want please print and get the values of both the variables, and get the clear picture that how will your code reach the "static" directory. Then try the code below
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
STATIC_PATH,
)
I'm trying to start a new project. In the tutorial it says I need to store the templates and static folders in the project folder. My project folder name is twjp. But for some reason if is store the the templates folder in twjp folder it doesn't work. it works only if I store it in the twjp/twjp folder. Below is my settings.py
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
TEMPLATE_PATH = os.path.join(PROJECT_PATH,'templates')
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.
TEMPLATE_PATH,
)
STATIC_PATH = os.path.join(PROJECT_PATH,'static')
STATICFILES_DIRS = (
STATIC_PATH,
)
"domainname/rango/ --> Doesn't work if I store templates in twjp/templates it works only if I store it in twjp/twjp/templates"
Tell me what ever you specs ie, Which version of django,python etc.
I hope this works for you, if not tell me i will update my answer too.
PROJECT_PATH = os.path.dirname(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(PROJECT_PATH, "static"),
)
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH,'templates')
)
This should your templates work with twjp/templates and twjp/static and not twjp/twjp.
I wanted to enable serving static files through django 1.5 builtin development server. I came across a strange problem.
If I make a request to my static file using localhost:8000/static/staticstyle.css then it responds me with 404 not found. But If I make a request to the same file without the value mentioned in the STATIC_URL and add the url pattern as "url(r'^anyval_other_than_mentioned_STATIC_URL/', django.views.static.serve,{'document_setting':settings.STATIC_ROOT}), ", then it responds me with 304 , which is conditional get.
I have collected all the static files in the static directory setup in the settings file and enabled all the context processor required for the template.
For production I have used nginx to serve the static file so there is no problem.
My settings.py looks like
STATIC_ROOT = APPLICATION_PATH+"/static/"
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('vendors',APPLICATION_PATH+'/vendors'),
('admin/assets/',APPLICATION_PATH+'/templates/admin/assets'),
# 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.
)
My application urls.py looks like
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Any hints would be highly appreciated.
Thank you .
please read this first
https://docs.djangoproject.com/en/1.5/howto/static-files/
There are some settings related to static files serve
The list of finder backends that know how to find static files in various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Absolute path to the directory static files should be collected to
STATIC_ROOT = os.path.join(APPLICATION_PATH, '..', 'static')
URL prefix for static files.
STATIC_URL = '/static/'
You can specify Additional locations of static files
STATICFILES_DIRS = (
os.path.join(APPLICATION_PATH, 'vendors'),
os.path.join(APPLICATION_PATH, '/templates/admin/assets'),
)
There is special application for static serve in django contrib
INSTALLED_APPS = (
...
'django.contrib.staticfiles',
...
)
After You have configured your project run collectstatic command
python manage.py collectstatic
This will copy all files from your static folders into the STATIC_ROOT directory.
In a development environment, I'd like to use static files from the app directories.
#settings.py
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATIC_ROOT = (os.path.join(SITE_ROOT, 'static_files/'))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(SITE_ROOT, 'static/'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_CONTEXT_PROCESSORS = (
#...
'django.core.context_processors.static',
#...
)
INSTALLED_APPS = (
#...
'django.contrib.staticfiles',
#...
)
I can find my static file if located in /static/css/file.css but not if in an_app/static/css/file.css.
Ok I found the problem, I made an oversight that was not visible in my question. I was searching into in static/js, static/flash, static/css, static/images and put the files directly into app/static so they were not found.
Check the value of STATIC_ROOT and STATICFILES_DIRS.
Add a print in your setting file.