I'm learning Django and have just moved everything to Cloud9. I don't understand how to point to my templates on Cloud9?
On my local machine I have the template directory set to /home/user/etc/etc/templates and it works fine. I can't seem to grasp what the path should be when putting it in Cloud9?
It's not realy good to use absolute and hardcoded path in your projects, just because you can work on different PCs or environments. So, you can define your project path according to your settings.py file. Place this somewhere in the begining of the settings.py:
import os
PROJECT_DIR = os.path.dirname(os.path.realpath(__file__))
So now you have variable PROJECT_DIR which will point to your Django project location on every PC and every env. And now, you can use it in your project in template dirs or in static files dirs like this:
# Like this
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
# Or like this, pointing to one dir UP
TEMPLATE_DIRS += (
os.path.join(PROJECT_DIR, '../templates'),
)
Also, if you settings file containt this rows:
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.Loader',
)
Your django application will automaticaly look for templates in you applications templates dir. For example
-apps
-main_app
-templates
-blog_app
-templates
You main_app and blog app templates dirs will be detected automaticaly, without adding them to templates_path.
Related
I have a project that has been running just fine for about 6 months. Static files have been working perfectly, and everything is great. I have my static files located in a folder as so:
/var/www/html/static/
In my settings.py file, I have the static section setup like so:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
'/var/www/html/static/',
)
This has been working just fine.
However, I now want to move the static folder to a different location. Specifically, I want to move it inside the main project directory. My project is located at /var/www/html/shq/ so I want to have my static directory located at /var/www/html/shq/static/. I moved the folder, then updated my settings.py file to look like this:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
'/var/www/html/shq/static/',
)
However, it didn't work. The Django project is still referencing the old location.
What am I missing here? Why isn't the Django project using the new location of /var/www/html/shq/static/?
EDIT
This is what the tail end of my settings.py file looks like:
119 STATICFILES_FINDERS = [
120 'django.contrib.staticfiles.finders.FileSystemFinder',
121 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
122 ]
123
124 STATIC_URL = '/static/'
125 STATIC_ROOT = '/var/www/html/collected_static/'
126 MEDIA_URL = '/media/'
127 MEDIA_ROOT = '/var/www/html/shq/media/'
128 STATICFILES_DIRS = [
129 os.path.join(BASE_DIR, "static"),
130 '/var/www/html/shq/static/',
131 ]
You might try doing something like this. I think it returns the list of directories that django looks for to find static files. Might help debugging.
from django.contrib.staticfiles import finders
from pprint import pprint
pprint(finders.find("", all=True))
Also, I may not be fully understanding your scenario, but you might confirm that the STATIC_ROOT is set to the location where you want to serve your static files (where your webserver will serve the files). The STATIC_DIRS setting tells collectstatic where to find static files, but the STATIC_ROOT is where collectstatic will actually place the files.
I figured it out. Not surprisingly, it was an easy fix once I figured it out.
It had nothing to do with my Django settings and everything to do with Apache.
Original
Alias /static/ /var/www/html/static/
So no matter what I did in my Django settings.py file, Apache was overriding that to send /static/ requested to the wrong directory.
New Apache Setting
Alias /static/ /var/www/html/shq/static/
Now the proper static files are being referenced. Hopefully this helps someone else in the future :)
My django application works well except for one application, all the static files are not loaded.
That happens on this url: http://localhost/db_mgmt/add/dg/. The template is loaded, but no css, no js.
When I look at one of the errors, the browser tries to load the page http://localhost/db_mgmt/add/static/jquery.min.js but the link should be: http://localhost/static/jquery.min.js
These files are loaded in base.html and work everywhere else...
Example of inclusion in base.html:
<script type="text/javascript" src="{{ STATIC_URL }}jquery.min.js"></script>
Here is my settings.py if it helps:
# Django settings for europolix project.
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
import os
#root of the project
PROJECT_ROOT=os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
#root of templates
TEMPLATE_ROOT=os.path.join(PROJECT_ROOT, 'templates')
#root of media files (import / export files)
MEDIA_ROOT=os.path.join(PROJECT_ROOT, 'media')
#root of static files (css, js, jquery...)
STATIC_ROOT=os.path.join(PROJECT_ROOT, 'static')
#WEB_ROOT=url of WSGIScriptAlias given in the apache configuration file (/etc/apache2/apache2.conf in Lubuntu 13.04)
#example: WSGIScriptAlias /europolix /var/www/europolix/europolix/wsgi.py -> WEB_ROOT="/europolix"
#in the apache configuration file, you must update the alias for static files as well
#ex: Alias /europolix/static /var/www/europolix/static -> WEB_ROOT="/europolix"
WEB_ROOT="/europolix"
#local
WEB_ROOT=".."
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.actrence.com/media/", "http://example.com/media/"
MEDIA_URL=WEB_ROOT+'/media/'
# URL prefix for static files.
# Example: "http://media.actrence.com/static/"
STATIC_URL=WEB_ROOT+'/static/'
# Additional locations of static files
STATICFILES_DIRS=(
STATIC_ROOT,
# 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.
)
TEMPLATE_DIRS=(
TEMPLATE_ROOT
# 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.
)
If I print those variables in my view I have the following paths:
PROJECT_ROOT /var/www/europolix
STATIC_ROOT /var/www/europolix/static
STATIC_URL ../static/
WEB_ROOT ..
Thanks in advance for your help.
Edit :
The variable WEB_ROOT is relative in local. Could it be the problem?
The variable searches in the parent directory (am I right?). So the applications with only one "child" in the url work (http://localhost/act or http://localhost/export) but not the applications with many "children" (e.g.: the one above, http://localhost/db_mgmt/add/dg/)
urls.py of the export app:
urlpatterns=patterns('export.views',
url(r'^/?$', 'export', name='export'),
)
urls.py of the db_mgmt app that does not work well:
urlpatterns=patterns('db_mgmt.views',
url(r'^add/(?P<field>\w+)/$', 'add', name='add'),
url(r'^form_add.html/(?P<field>\w+)/$', 'form_add', name='form_add'),
)
We would need to know more about the differences between the applications that work and the application that is giving you trouble
As I thought, the problem, one of the problems was about the WEB_ROOT variable.
Here is how I fixed it:
WEB_ROOT="http://127.0.0.1:8000"
Another problem was the path of the template of my application db_mgmt:
url="/db_mgmt/form_add.html/"+field+"/"
I had to remove the first slash to have it work:
url="db_mgmt/form_add.html/"+field+"/"
Solved :).
My templates are not recognized and I'm getting the following error.
os.path.dirname(__file__)+'\\template' NameError: name 'os' is not defined
The code which I have used in settings is:
os.path.dirname(__file__)+'\\template'
what should I do now.
You could see the relevant knowledge in Definitive Guide to Django Page 99:
import os.path
TEMPLATE_DIRS =(os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'),)
Where explains how it works
This example uses the “magic” Python variable file, which is automatically set
to the file name of the Python module in which the code lives. It gets the name of the
directory that contains settings.py (os.path.dirname), joins that with templates in a
cross-platform way (os.path.join), then ensures that everything uses forward slashes
instead of backslashes (in the case of Windows).
Import the module os
import os
os module is missing You have used it without importing
Add this in your settings.py
import os
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)
and place all your templates under templates folder in your project
and you can use absolute paths like linux(/home/your_project/../templates) in windows ("C:/your_project/../templates")
but it is not good practice
2022 answer.
Keep templates folder in the same directory as the manage.py file
#settings.py
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = os.path.join(BASE_DIR,'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR],
...
urlpatterns = patterns('',
# Examples:
url(r'^$', 'core.views.homepage', name='homepage'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
That's my urls.py
The static file works if I disable the DEBUG, and doesn't work If I turn it back on.
Part of my settings
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# 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',
)
Really strange to me, can anyone help?
No, STATIC_ROOT is not served by Django ever. In production (debug off), it is expected that your web server will serve this directory directly. In development (debug on), you shouldn't have this directory or anything in it, anyways.
Let me say that again for emphasis. You are never supposed to directly save any assets in STATIC_ROOT. This directory is solely for the output from the collectstatic management command. All assets in your project are supposed to be saved in the static directory of the particular app it belongs to.
Now, of course, you'll often have assets that are not directly related to a single app, but rather your entire project as a whole. For this scenario, you create a separate directory in your project and place all common assets there. You then add this directory to the STATICFILES_DIRS setting.
In development, Django will serve anything in that directory, and in production, the collectstatic management command will pull assets from that directory into STATIC_ROOT.
I'm developing Django apps on my local windows machine then deploying to a hosted linux server. The format for paths is different between the two and manually replacing before deployment is consuming more time than it should. I could code based on a variable in my settings file and if statements but I was wondering if anyone had best practices for this scenario.
The Django book suggests using os.path.join (and to use slashes instead of backslashes on Windows):
import os.path
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)
I think this is the best solution as you can easily create relative paths like that. If you have multiple relative paths, a helper function will shorten the code:
def fromRelativePath(*relativeComponents):
return os.path.join(os.path.dirname(__file__), *relativeComponents).replace("\\","/")
If you need absolute paths, you should use an environment variable (with os.environ["MY_APP_PATH"]) in combination with os.path.join.
We have a situation very similar to yours, and we've been using different paths in settings, basing on sys.platform.
Something like this:
import os, sys
DEVELOPMENT_MODE = sys.platform == 'win32'
if DEVELOPMENT_MODE:
HOME_DIR = 'c:\\django-root\\'
else:
HOME_DIR = '/home/django-root/'
It works quite OK - assumed all development is being done on Windows.
Add
import os.path
BASE_PATH = os.path.dirname(__file__)
at the top of your settings file, and then use BASE_PATH everywhere you want to use a path relative to your Django project.
For example:
MEDIA_ROOT = os.path.join(BASE_PATH, 'media')
(You need to use os.path.join(), instead of simply writing something like MEDIA_ROOT = BASE_PATH+'/media', because Unix joins directories using '/', while windows prefers '\')
in your settings.py add the following lines
import os.path
SETTINGS_PATH = os.path.abspath(os.path.dirname(__file__))
head, tail = os.path.split(SETTINGS_PATH)
#add some directories to the path
import sys
sys.path.append(os.path.join(head, "apps"))
#do what you want with SETTINGS_PATH