Django Template Not Found

2019-04-21 08:03发布

问题:

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

回答1:

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.



回答2:

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).



回答3:

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.