Django get static media files - django

All, i am using Django1.4,i have a question regarding accessing the img files,js files etc... I have my files in the directory /opt/lab/labsite/media/img for images and /opt/lab/labsite/media/js for javascript files.What should i change the settings in the setting files such that the below html works..I am using django server to run the code
My code is currently located in /opt/lab/labsite/settings.py and other modules lies in /opt/lab/labsite/.........
<img src="/media/img/logo.jpg" alt="logo" />
Below are the settings in the settings.py file
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/opt/lab/labsite/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# 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: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/opt/lab/labsite/media/'
Changes
MEDIA_ROOT = '/opt/lab/labsite/media/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/opt/lab/labsite/static/'
STATIC_URL = '/static/'
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',
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'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 = 'labsite.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'labssite.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.
'/opt/lab/labsite/templates'
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'home',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth'
)
HTML:
<img src="{{ STATIC_URL }}img/hi.png" alt="Hi!" />
<img src="/static/img/hi.png" alt="Hi!" />
<img src="/media/img/hi.png" alt="Hi!" />
<img alt="Hi!" src="/opt/ilabs/ilabs_site/media/img/hi.png">

STATIC_URL you have set doesn't look good. I think that should be STATIC_ROOT.
You should set (for example) MEDIA_URL='/media/' and STATIC_URL='/static/' and I hope you have also enabled static file serving in urls.py

Set this in settings.py:
STATIC_ROOT = '/opt/html/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
'/opt/lab/labsite/static/',
)
add this in context processors:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.static',
...
)
and don't forget this in INSTALLED_APPS:
'django.contrib.staticfiles',
and then:
<img src="/static/img/logo.jpg" alt="logo" />
or
<img src="{{ STATIC_URL}}img/logo.jpg" alt="logo" />
if logo.jpg is located in /opt/lab/labsite/static/img/
In addition, STATIC_ROOT serves as a static folder to be served by Web servers/reverse proxies like Apache, Nginx, etc. If you invoke:
python manage.py collectstatic
This will copy all files from /opt/lab/labsite/static/ to STATIC_ROOT - /opt/html/static/. This is useful for deployments.
But all this is for development. For production there are better ways to serve static content - https://docs.djangoproject.com/en/dev/howto/static-files/#staticfiles-production

Related

Using Whitenoise but still can not serve static files

I'm trying to serve static files in my product review website, and I'm using Whitenoise, but It didn't work (can not find the files in /static) (when I test on local with DEFAULT = False, it still works)
I've tried to config wsgi file instead of using whitenoise middleware
This is my some code in my settings file to serve static.
DEBUG = False
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'djangobower.finders.BowerFinder',
)
Can you show me how to fix it? Pardon for my English
I tried to config the settings again:
DEBUG = False
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# I don't have STATICFILES_DIRS, is it wrong?
STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage"
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'djangobower.finders.BowerFinder',
)
But it still can not serve static files
I believe what you're missing is the STATICFILES_STORAGE. This is my settings.py related configuration.
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
ALLOWED_HOSTS = ["*"]
I followed the below configuration settings to resolve the issue.
DEBUG = False
ALLOWED_HOSTS = ['testnewapp.herokuapp.com']
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'widget_tweaks',
'phonenumber_field',
'django_extensions',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
# Whitenoise Storage Class - Apply compression but don’t want the caching behaviour
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
# Comment the below line
# django_heroku.settings(locals())
Things to Remember
Make sure you’re using the static template tag to refer to your static files, rather that writing the URL directly. For example:
{% load static %}
<img src="{% static "images/error.jpg" %}" alt="OOps!" />
<!-- DON'T WRITE THIS -->
<img src="/static/images/error.jpg" alt="OOps!" />
If you get an error message with collectstatic, simply disable it by instructing Heroku to ignore running the manage.py collecstatic command during the deployment process.
But if you need to use WhiteNoise with any WSGI application
You need to wrap your existing WSGI application in a WhiteNoise instance and tell it where to find your static files. For example:
from my_project import MyWSGIApp
application = MyWSGIApp()
application = WhiteNoise(application, root='/path/to/static/files')
application.add_files('/path/to/more/static/files', prefix='more-files/')
Note
These instructions apply to any WSGI application. However, for Django applications you would be better off using the WhiteNoiseMiddleware class which makes integration easier.
#
http://whitenoise.evans.io/en/stable/base.html

TEMPLATE_DIRS and templates folder help please

So I'm pulling apart a website with the front-end already built and have taken on the task of building out the backend, but I am new to django. I have managed to separate everything out accordingly (css, js, img's in a static folder, html files in a templates folder, etc) and so far have been able to set the index.html as the homepage to django. Within this index.html file, other html files (located in the templates folder along with the index.html file) are being loaded within tags of the index.html file. Currently all of the images, css, and js is coming through in the file, but the html files are not. I am referencing these html files as "name of file.html" However, I cannot seem to get these to load unless I move the templates folder into the static folder (alongside the css, images, js, etc.) and change the reference to "static/templates/name of file.html"
My project setup is as follows. Also I'm running django 1.7.
atmos_v4/
atmos_v4/
init__.py
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py
static/
css/
...
img/
...
js/
...
media/
...
templates/
index.html
...
My urls.py and settings.py are below. I have a feeling my TEMPLATE_DIRS and STATIC_ROOT may be set up incorrectly. If not, would someone be so kind as to tell me what I'm missing? Thank you!
settings.py:
"""
Django settings for atmos_v4 project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y=3ey3sv8lm1j358(2bgthtx0bzy_cjaxug#2npx029nfs#5i%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'atmos_v4.urls'
WSGI_APPLICATION = 'atmos_v4.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
from os.path import join
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
STATIC_PATH = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = (
STATIC_PATH,
)
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="index.html")),
url(r'^admin/', include(admin.site.urls)),
)
index.html reference examples
<div id="wheelartist" style="position:absolute; top:131px; left:536px; z- index:999999;">
<div id="circleartist" class="circleartist">
<a id="homebuttonLink" href="artist_profile.html"><img id="homebutton" title="Home" src="/static/img/icons/user.png" alt=""></a>
<a id="msgsbuttonLink" href="messages.html"><img id="msgsButton" title="Messages" src="/static/img/icons/mail.png" alt=""></a>
<a id="directorybuttonLink" href="directory.html"><img id="directoryButton" title="Directory" src="/static/img/icons/book.png" alt=""> </a>
<a id="cartbuttonLink" href="shopping_cart.html"><img id="cartButton" class="shopingCart" title="Shopping Cart" src="/static/img/icons/shopping.png" alt=""></a>
<a id="contestsbuttonLink" href="contests_list.html"><img id="contestsButton" class="planet" title="Planet" src="/static/img/icons/planet.png" alt=""></a>
<a id="pointsbuttonLink" href="points.html"><img id="pointsButton" class="awards" title="Awards" src="/static/img/icons/awards.png" alt=""></a>
<a id="prefbuttonLink" href="preferences.html"><img id="prefButton" class="tools" title="Tools" src="/static/img/icons/tools.png" alt=""></a>
<a id="searchbuttonLink" href="search.html"><img id="searchButton" class="headphones" title="Search" src="/static/img/icons/music.png" alt=""></a>
<a id="mapbuttonLink" href="artist_careermap.html"><img id="mapButton" title="Career Map" src="/static/img/icons/map.png" alt=""></a>
<a id="profitsbuttonLink" href="artist_profits.html"><img id="profitsButton" title="Profits" src="/static/img/icons/profits.png" alt=""></a>
<a id="statsbuttonLink" href="artist_stats.html"><img id="statsButton" title="Stats" src="/static/img/icons/stats.png" alt=""></a> </div>
templates/
index.html
try to change to this structure
templates/
atmos_v4/
index.html
and inside the settings.py remove this
"from os.path import join"
EDIT: after you update your file now i see that you have bad index.html file, you need to use the built-in function for templates and url
https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#url

Django and Heroku: Static files work with 'foreman start' but not './manage.py runserver'

I have added my own answer to the answers below, this has been solved.
I am able to serve up static files when powering up the server using the heroku tool foreman:
$ foreman start
12:25:21 web.1 | started with pid 33574
12:25:21 web.1 | 2013-04-10 12:25:21 [33577] [INFO] Starting gunicorn 0.17.2
12:25:21 web.1 | 2013-04-10 12:25:21 [33577] [INFO] Listening at: http://0.0.0.0:5000 (33577)
12:25:21 web.1 | 2013-04-10 12:25:21 [33577] [INFO] Using worker: sync
12:25:21 web.1 | 2013-04-10 12:25:21 [33582] [INFO] Booting worker with pid: 33582
but they static files aren't served up using runserver:
$ ./manage.py runserver
Validating models...
0 errors found
April 10, 2013 - 12:26:06
Django version 1.5, using settings 'myproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
My Procfile:
web: gunicorn myproject.wsgi
My settings.py (some settings removed):
import os
import logging
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# Using local_settings for this
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Heroku specific database settings, overridden for local dev in local_settings.py (not in git)
import dj_database_url
DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure() (also needed for Heroku)
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/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(PROJECT_PATH, '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 = (
# 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',
)
# 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.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.doc.XViewMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
# Uncomment the next line for simple clickjacking protection:
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'myproject.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'myproject.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(os.path.dirname(__file__), "templates"),
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages"
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.humanize',
'django.contrib.flatpages',
'debug_toolbar',
'stripe',
'notification',
'south',
'registration',
'timedelta',
'sorl.thumbnail',
'django_messages',
'tinymce',
)
try:
from local_settings import *
except ImportError:
pass
My main urls.py:
from django.conf.urls import patterns, include, handler500, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', 'myproject.views.root', name='root'),
(r'^admin/', include(admin.site.urls)),
)
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
As the title says I'm able to load all my static assets using foreman start but not when running ./manage.py runserver.
I've also ran ./manage.py collectstatic so I know all the static files are in the correct directory.
My static and media folders both live under the myproject folder, as well as settings.py and the main urls.py.
You have to add the (absolute) path to the directory which contains your static files to STATICFILES_DIRS in the settings. You don't neet to run collectstatic
I finally got it working so that static files can be loaded via runserver and deploying to heroku also works.
Things I changed:
settings.py: Didn't change anything here, instead I will override some settings in my local_settings.py file.
STATIC_ROOT = os.path.join(PROJECT_PATH, '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 = (
# 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.
)
local_settings.py:
Added the following:
STATIC_ROOT = ''
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_PATH, 'static'),
)
This allows heroku to serve up your static files as well as runserver for development. It's also worth re-mentioning that I needed the extra static url patterns added to the end of my urls.py to get serving up static media in heroku.
This is expected. Django doesn't serve static files. Heroku (apparently) does.
To serve files locally, you need to add a route in urls.py to serve the files.

A simple static file location issue

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'),
)

django: cannot find static files

I ran into this problem for quite some time and is having trouble solving this. Right now I am using django 1.2.4 and having the following settings:
AUTH_PROFILE_MODULE = 'customUsers.UserProfile'
TEMPLATE_STRING_IF_INVALID = 'Error generating variable'
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ANONYMOUS_USER_ID = -1
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend', # default
'guardian.backends.ObjectPermissionBackend',
)
MANAGERS = ADMINS
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
# "django.core.context_processors.static", there is no this function in the file
"django.contrib.messages.context_processors.messages",
"customUsers.user_cp_context.userCPContext")
USE_I18N = False
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/Users/carrier24sg/Documents/workspace/static_teachers/'
# 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 = '/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/admin/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '(grqejktuccy6!#5pr#535*vivl#lcv06=v*hvae#&6mx15nzt'
# 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.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
#ROOT_URLCONF = 'myproject.urls'
#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.
# '/home/carrier24sg/webapps/django/myproject/templates'
#)
SITE_ID = 2
ROOT_URLCONF = 'teachers.urls'
TEMPLATE_DIRS = (
'/Users/carrier24sg/Documents/workspace/templates',
'/Users/carrier24sg/Documents/workspace/teachers/templates'
)
INSTALLED_APPS = (
'customUsers',
'ConsentForm',
'teachers.consent_teachers',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'conversation',
'teachers.student_profiling',
'south',
'guardian',
'persistent_messages',)
For some reasons I cannot serve static files like js and css. The output of the development server displays 404 error "GET /media/common/css/sidebar.css HTTP/1.1" 404 2202 I have tried entering the url for the static file on browser, instead of telling me that the file cannot be found(which i was expecting), I was shown the url-unmatched django debug page Using the URLconf defined in teachers.urls, Django tried these URL patterns, in this order: ......The current URL, media/js/conversation_load.js, didn't match any of these.
Question: why is django not reading the url http://127.0.0.1:8000/media/js/conversation_load.js like a request for static file?
for example, you have your "media" folder near settings.py
Then try:
from os import path
MEDIA_ROOT = path.join(path.dirname(__file__), 'media')
Where "media" is you media folder name.
In urls.py:
from os import path
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': path.join(path.dirname(__file__), 'media')}),
Have you added into your templates:
{% load staticfiles %}
This loads what's needed.