I have a Django problem which only occasionally has problems finding Templates. It will be running fine for hours, and then suddenly not be able to serve certain templates. Occasionally the problem will correct itself, but can always be fixed by running touch <template>. My current solution is a cronjob which executes touch <project root> every minute, and that works so long as cron keeps up. However, I want to figure out a proper solution to my problem.
Relevant Settings:
PROJECT_ROOT = os.path.dirname(__file__)
APPS_ROOT = os.path.abspath(os.path.join(PROJECT_ROOT, "apps"))
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
TEMPLATE_DIRS = (
(PROJECT_ROOT + '/templates'),
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.request",
"django.core.context_processors.i18n",
"django.contrib.messages.context_processors.messages",
"base_site.context_processors.app_list"
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Just wanted to add another case where you may get the Template Does Not Exist error.
Make sure you've added your app in the INSTALLED_APPS variable inside your settings.py file. The startapp command is not enough.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myappname', # add your app here :)
]
I know it's silly, but I know people that have failed their driver's test because of forgetting to fasten their seat belt, so forgetting a line of code isn't as rare as it sounds.
Try updating your settings like so:
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, 'templates'),)
(This is the default way of getting the BASE_DIR in django 1.8). Prior to Python 3.4, __file__ is not guaranteed to give the absolute file path.
You should also try and remain platform agnostic by using os.path.join rather than adding the directory as a string (other platforms use backslashes).
So it turns out my problem was not with Django itself but with my environment. I was running the Django server from ~/Django-project, and our dev server encrypts home directories once all sessions are signed out which means the service could no longer find it. Moving the project to /var/ and daemonizing the manage.py runserver command has kept the project free of Template Does Not Exist errors.
Related
I am able to create a Django Project and and my admin site works fine initially. After I create an app, register it, setup static files, the Django Admin page actually starts complaining that I failed to give it static files at all. (Something I don't consider myself to be on the hook for)
So when I hit: http://127.0.0.1/admin (like I always do), somewhere in the timeline, I face an error that says:
TemplateSyntaxError at /admin/login/
Invalid block tag on line 4: 'static', expected 'endblock'. Did you forget to register or load this tag?
Okay so that seems like a silly question, but why am I being asked if I registered the static tag? What about my static tag destroyed theirs? I'm not even sure which files I should be looking at right now.
In settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
DEBUG = True
... snip - irrelevant stuff
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, ‘myapp', 'static'),
]
The file that is breaking down isn't mine to edit. It's the admin one. Where should I be looking? I should also note that my own app also no longer is able to load it's static files and returns the same error now.
TL;DR: "How can one accidentally disable all static files for the development site? How does one restore that functionality?"
Update 2018-09-10:
I shipped the whole application from my Windows 10 laptop to my Linux machine and the application booted perfectly on Ubuntu 18.04. I've made no file changes, other than regenerating my virtualenv from the same requirements file.
I'm using Django version 1.10. Project work fine on Debug = True, but when I set it to False is not. Django just can't find static files.
My Django settings looks like:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'master',
'update',
]
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
And the urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^master/', include('master.urls')),
url(r'^update/', include('update.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
uwsgi.ini file
[uwsgi]
chdir = %v
virtualenv = %v/py
module = go_conf.wsgi
master = true
http = :8000
vacuum = true
buffer_size = 64k
max-requests = 100
daemonize = %v/log.txt
I aslo used python manage.py collectstatic, and it collected everything but still not working.
I tried to solve this by reading other articles on this site, but nothing really worked for me.
Hope, that someone will at last help.
This is the Django desing. A quote from the docs for Static file development view:
This view will only work if DEBUG is True.
That’s because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.
If you are setting DEBUG=False you are probably going to make it production. If so, your static files must be served by a webserver (eg. Nginx, Apache etc).
check the whitenoice library,
it works great for development and production environment
Radically simplified static file serving for Python web apps
I am getting the following error:
TemplateDoesNotExist at /app1/1/about/
index/index.html
but Template-loader postmortem says:
/var/www/web/sites/mysite.com/app1/templates/index/index.html (File exists)
I have tried all stackoverflow's answers on similar questions, but they didn't work for me. On my local server(running on OSX, virtualenv) everything is alright, but on production server I'm getting this error. On production server I'm using Django 1.7.5 on Ubuntu 14 with virtualenv.
Each app has it`s own template, the structure is like this:
app1
--templates
----index
------index.html
------head.html views.py app2
--templates
----index
------index.html
------head.html views.py
In settings.py I have the following parameters for templates:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DEBUG = True
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates'),]
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
INSTALLED_APPS = (
# django
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# widgets
'widget_tweaks',
'compressor',
'tinymce',
'django_activeurl',
'debug_toolbar',
# modules
'app1',
'app2',
)
and including them in views like this:
template_event = loader.get_template('index/materials.html', dirs=["app1/templates/"])
You have confused the template loader by passing in the dirs argument, which overrides whatever is in TEMPLATE_DIRS.
First, you don't need to set TEMPLATE_DIRS if all your templates are included inside app directories. The TEMPLATE_DIRS variable exists if you want to load templates from other file system locations. If all your templates are in app/templates/, then you don't need to set TEMPLATE_DIRS.
Since you are trying to load a template that is part of an application, simply pass the relative path to the template:
template_event = loader.get_template('index/materials.html')
Now, here is what django is gong to do (highly simplified):
First, it will look at TEMPLATE_LOADERS and then call each of the loader for its templates. The first loader is the file system loader, which will use the TEMPLATE_DIRS setting to find any templates. If a template here matches the path, then it will stop.
The next loader is the app_directories loader, this loader will look for a directory named templates in any app that is added to INSTALLED_APPS and then return the first template that matches.
The postmartem is telling you that the loaders have found your template, but the way you are asking them to load templates - they cannot find the template.
Just realized my mistake, after deep reading of django documentation, figured out that Alsadair was right with his answer in comments.
Usually, the recommendation is to put an app1 subdirectory i.e.
app1/templates/app1/, and load app1/index/materials.html. Then dirs is
unnecessary, in load_templates, and the template should be loaded from
the correct directory.
I'm learning django with this excellent book "Practical Django Projects". I was able to follow the steps of the book perfectly, but now I stumbled upon the following problem.
When creating the page http://127.0.0.1:8000/first-page/ as image below:
I found the following error page:
Slightly different of this one, announced on book (page 16):
Then, I openned the file urls.py and added to it the following line of code:
(r'', include ('django.contrib.flatpages.urls')),
And the code looks like this:
I saved urls.py and accessed http://127.0.0.1:8000/first-page/ again, finding the same error message above (nothing changed), when, according to the book, I should now have found this other error page:
As a result, after I create the directory and file default.html for templates, as follows:
And have changed the TEMPLATE_DIRS settings.py file like this:
Again, the http://127.0.0.1:8000/first-page/ shows that same error message when, this time should show this:
I have repeated several times the steps.
I'm using Python 2.6 and django 1.1 (the same version of the book).
Does anyone have any idea about what I'm doing wrong?
Thank you in advance for any help.
It all seems so simple and straightforward. And yet, does not work!
Here my settings file code:
# Django settings for cms project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'C:\Projetos\cms\cms.db' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
MEDIA_ROOT = ''
MEDIA_URL = ''
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = ''
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'cms.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.
'C:/Projetos/templates/',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.flatpages',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
)
The answer to all errors was this (thanks, mongoose_za):
"On page 15 [of the book "Practical Django Projects"] you must make sure you edit the example.com site instead of adding a new site. You might have noticed in your settings.py the SITE_ID = 1. If you add a new site 127.0.0.1:8000 then that will have a SITE_ID of 2, and in the following section flatpage views filter by default on the current site which is 1."
So, I just change SITE_ID = 2 (instead of 1) in settings.py, because I had added a new site 127.0.0.1:8000.
After that, I changed the path to my templates folder according to instructions on the book to:
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.
'C:/Projetos/templates/',
)
I found the expected result (the blank page "My first page")
I also have followed this advice:
"On p13 is where the first deviation from the older django kicks in. In your settings.py add 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', (don't forget the comma) to your MIDDLEWARE_CLASSES."
All this was found on this great blog:
http://blog.haydon.id.au/2008/08/2-your-first-django-site-simple-cms.html
Firstly: the template does not exist error is because you dont have the template
C:/Projects/templates/flatpages/default.html (also in your screenshot your template dir is spelled "Projetos")
Secondly: you shouldnt need to add any the url rule for flatpages. Flatpages works via middleware:
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
so within your settings file:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'django.middleware.common.CommonMiddleware',
#'debug_toolbar.middleware.DebugToolbarMiddleware',
)
The TemplateDoesNotExist error is not on your template, but on 500.html. There's an error in your code in your template or view and Django is responding with a 500 error. However, in development, you should have DEBUG = True, in which case Django will show a stacktrace instead of trying to load 500.html.
So the simple solution is to make DEBUG = True so you can see the real error and correct that. However, you'll still need 500.html when you finally launch, so you might as well go ahead and create that too.
I have a django (v1.1.1) on a server running Python 2.4. On my localhost/development computer the site works perfect. When I uploaded the files to the production server, it seemed to work fine, but after a page refresh I am receiving random TemplateDoesNotExist errors.
In the trace report I looked at the TEMPLATE_DIRS variable to make sure I was pointing to the right place, and it actually changes each time I refresh the page between this:
TEMPLATE_DIRS
('templates', '/var/www/vhosts/mysite.com/apps')
and this
TEMPLATE_DIRS
('templates', '/var/www/django-sites/apps/templates')
How is it possible that django/python is looking in two different locations when I refresh the page? After 3-4 attempts it suddenly works until I either refresh or go to the next page. The correct location is /var/www/vhosts/mysite.com/apps/templates which is definted in my settings.py file:
# Django settings for django-sites project.
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql'
DATABASE_NAME = 'mysite'
DATABASE_USER = 'mysuser'
DATABASE_PASSWORD = 'mypass'
DATABASE_HOST = 'www.mysite.com'
DATABASE_PORT = ''
# 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.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# 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 = ''
# URL prefix for admin media -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'mysecretkey'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'apps.urls'
URL_ROOT_LEAD_CAPTURE = '/lead-capture/'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.core.context_processors.auth',
)
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates'),
'/var/www/vhosts/mysite.com/apps/templates',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.admindocs',
)
I appreciate the help!
It sounds like a problem with your apache configuration or what ever you are using for the web server. The PROJECT_ROOT:
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
Is dependent upon the current absolute path which is set by what ever environment is running the application. Make sure that only one route for handling URLs exists in your web server configuration.
Second, make sure all django environments have been cleanly shutdown, you may have some old, misconfigured environments around serving requests.