This is my project tree:
projectname
projectname
init.py
settings.py
urls.py
wsgi.py
appname
init.py
admin.py
models.py
test.py
views.py
urls.py
templates
base.html
login.html
Now in the settings.py I am using this code:
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "projectname", "templates"),
)
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "projectname", "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "projectname", "static", "media")
How can I get the path of the project directory, so that I don't need to type the project name projectname in the code and use that code in any other django project?
Update
Or can I just use this
BASE_DIR+'/templates'
BASE_DIR+'/static/media'
Or is it a bad idea?
I would suggest you to use os.path.abspath:
# Project root is intended to be used when building paths,
# e.g. ``os.path.join(PROJECT_ROOT, 'relative/path')``.
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
# Absolute path to the directory where ``collectstatic``
# will collect static files for deployment.
#
# For more information on ``STATIC_ROOT``, visit
# https://docs.djangoproject.com/en/1.8/ref/settings/#static-root
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
# Absolute path to the directory that will hold uploaded files.
#
# For more information on ``MEDIA_ROOT``, visit
# https://docs.djangoproject.com/en/1.8/ref/settings/#media-root
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'uploads/')
BASE_DIR already includes "projectname". When you do os.path.dirname(BASE_DIR), you go up a level from projectname; only to add it back in. Don't do that.
Instead, just use BASE_DIR directly:
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, "templates"),
)
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.
Have a problem with connecting css to my template.
My project root is
"D:/birzha/", static path is "D:/birzha/static/", css in
"D:/birzha/static/css/template.css".
What STATIC_ROOT or STATICFILES_DIRS should I use for correctly viewing css file? I tried so much turns, but nothing happens, css still off.
First of all you need to tell where all your static files will be "collected", place the following lines in settings.py:
BASE_DIR = (os.path.dirname(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
Then you need to make a static folder within your app and the hierarchy
should be like this appname/static/appname/css.
Finally run the command python manage.py collectstatic and type yes on prompt. This will copy all of your static files within a folder that you specified in STATIC_ROOT
Now you can access your static files by giving the path like,/static/appname/css/mystyle.css
You can try this
Site root will contain you project root path. You can change "/templates" with static
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
# calculated paths for django and the site
# used as starting points for various other paths
TEMPLATE_DIRS = (
os.path.join(SITE_ROOT, 'templates/'),
)
MEDIA_ROOT = os.path.join(SITE_ROOT, 'templates/media/')
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/'),
)
I am new to Django. I am using django administration for basic crud purpose.
I found that template for django admin resides at
C:\Python27\Lib\site-packages\django\contrib\admin\templates\admin
I need to change it as my own location .. i created one folder "template" on base dir of project and added following lines
STATIC_URL =os.path.join(BASE_DIR, 'templates')+'/'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
i copied all files from C:\Python27\Lib\site-packages\django\contrib\admin\templates to basedir/templates
but still it is referencing to C:\Python27\Lib\site-packages\django\contrib\admin\templates
what is the best way?
try this,hope this helps you
import os
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
...
#MEDIA_ROOT = PROJECT_PATH + '/media/'
TEMPLATE_DIRS = (
PROJECT_PATH + '/templates/'
)
STATIC_ROOT = '%s/site_media' % PROJECT_DIR
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(STATIC_ROOT, 'images'),)
When I run 127.0.0.1:8000/static/something.jpg everything works.
But I want get something.jpg like this 127.0.0.1:8000/static/images/something.jpg
When I change STATICFILES_DIRS:
STATICFILES_DIRS = ('',)
127.0.0.1:8000/static/images/something.jpg doesn't work, why?
Use
STATICFILES_DIRS = (os.path.join(STATIC_ROOT, ''),)
Your STATIC_DIR should point to the project site_media dir. When adding images' to it, then 127.0.0.1:8000/static/images/something.jpg is being searched in .../site_media/images/images/something.jpg