django. Templates working local but not on pythonanywhere.com - python

I have a working project in django when I run it local but not when I run it on pythonanywhere.com. I get error TemplateDoesNotExist.
How do I make it run on pythonanywhere.com?
Do i have to do something in the code or in pythonanywhere web app settings?
Thanks!
My code:
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)

You shouldn't use the relative directory 'templates' in your TEMPLATES setting. Try changing DIRS to:
'DIRS': [os.path.join(BASE_DIR, 'templates')],

Related

Forking Django Oscar's static files doesn't work

I'm trying to fork default oscar's static. My folder structure is the following:
myproject/
static/
oscar/
templates/
flatpages/
oscar/
myproject/
And I set the following settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / 'static/'
]
Forking templates works just fine, but the same thing doesn't work with static, default files are still served in HTML. To fork static I used this command:
./manage.py oscar_fork_static
Any idea why is it so?
Add this inside templates in settings.py file
'libraries' : {
'staticfiles': 'django.templatetags.static',
EX:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'libraries' : {
'staticfiles': 'django.templatetags.static',
}
},
},
]
}
See if this is helps you

ImportError: cannot import name 'OSCAR_MAIN_TEMPLATE_DIR'

I have been trying to install django-oscar but it gives me this error when I try to make migrations (via : python manage.py migrate).
ImportError: cannot import name 'OSCAR_MAIN_TEMPLATE_DIR' from 'oscar'
(C:\Users\dell\Envs\eshop\lib\site-packages\oscar__init__.py)
Code I am using:
from oscar import OSCAR_MAIN_TEMPLATE_DIR
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
OSCAR_MAIN_TEMPLATE_DIR
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.contrib.messages.context_processors.messages',
'oscar.apps.search.context_processors.search_form',
'oscar.apps.promotions.context_processors.promotions',
'oscar.apps.checkout.context_processors.checkout',
'oscar.apps.customer.notifications.context_processors.notifications',
'oscar.core.context_processors.metadata',
],
},
},
]
From the release notes for 2.0+ (2019-07-04):
OSCAR_MAIN_TEMPLATE_DIR setting has been removed and existing templates updated with the full path. See issue:1378, issue:2250. Please update your templates accordingly.

Jinja2 templating options not working in test, but are fine when running server

I receive the following error...
ERRORS:
?: (templates.E001) You have 'APP_DIRS': True in your TEMPLATES but also specify 'loaders' in OPTIONS. Either remove APP_DIRS or remove the 'loaders' option.
...when attempting to run any test suite, with Django 1.11 and its standard test runner.
manage.py runserver, however, works just fine.
I tracked the error back to the jinja2 templates. My django TEMPLATES setting looks like:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [os.path.join(BASE_DIR, 'jinja2')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'environment': 'mysite.jinja2.environment',
},
},
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(BASE_DIR, 'templates')],
"APP_DIRS": True,
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'mysite.context_processors.app_rendering_ctx',
],
},
},
]
You'll see there's no loaders key in either of the OPTIONS dicts, so the error is seriously confusing.
Stripping out, it's nothing to do with the context processors or environments. It's related to the jinja2 templating...
Removing the APP_DIRS key from the first entry lets the tests run:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [os.path.join(BASE_DIR, 'jinja2')],
'OPTIONS': {
#stuff
},
},
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(BASE_DIR, 'templates')],
"APP_DIRS": True,
'OPTIONS': {
#stuff
},
},
]
But now I can't find the jinja2 templates in my app directories, so visiting the site gives TemplateNotFound errors (of course!).
Does the jinja2 templating engine dynamically attach a loaders key to its own options dict? And why does the test runner fail with this when the server runs happily?
I'm not going to tick this as selected answer, since it's a workaround not a solution... but others can get over this by manually adding the APP_DIRS they want to search into the DIRS key:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [os.path.join(BASE_DIR, 'jinja2'),
os.path.join(BASE_DIR, '..', 'myapp', 'jinja2'),
os.path.join(BASE_DIR, '..', 'myotherapp', 'jinja2')],
'OPTIONS': {
#stuff
},
},
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(BASE_DIR, 'templates')],
"APP_DIRS": True,
'OPTIONS': {
#stuff
},
},
]
Of course, this is neither a generic solution nor easily replicated if you have many apps. For just a few its fine.

Django localhost gives 500 Error Server Error when DEBUG = False, however ALLOWED_HOSTS=['*']

EDIT: MORE INFORMATION:
I added logging as suggested in the first answer, and got this:
ValueError: The file 'file/name' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object
ORIGINAL POST:
I'm running my Django site on locally, and when DEBUG=True it works fine. However, when I set DEBUG=False, it returns a 500 Server Error.
ALLOWED_HOSTS has been set to ['*'], and it still returns a 500 Server Error.
Here's my settings.py:
import os
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "**************************"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# Application definition
INSTALLED_APPS = [
'my_app.apps.MyAppConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
# Disable Django's own staticfiles handling in favour of WhiteNoise, for
# greater consistency between gunicorn and `./manage.py runserver`. See:
# http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'debug': DEBUG,
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'my_db',
'USER': 'admin',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'static'),
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
The right way to approach this is to enable logging and Django itself will (usually) indicate the problem. The advantage of this approach is that it will be useful for future problems as well. Here's a sample logging setup that will log with DEBUG=false (borrowed from this answer):
# settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'mysite.log',
'formatter': 'verbose'
},
},
'loggers': {
'django': {
'handlers':['file'],
'propagate': True,
'level':'DEBUG',
},
'MYAPP': {
'handlers': ['file'],
'level': 'DEBUG',
},
}
}

Django templates and unipath

I'm trying to use unipath module in my django project as it mentioned in Two Scoops of Django book and something works not as intended.
In my settings.py I have this:
from unipath import Path
BASE_DIR = Path(__file__).ancestor(2)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [(BASE_DIR.child('templates'),)],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_ROOT = BASE_DIR.child('static')
MEDIA_ROOT = BASE_DIR.child('media')
And with that settings I'm getting TemplateDoesNotExist exception:
Using loader django.template.loaders.filesystem.Loader:
/var/www/(Path('/home/user/my_project/project/templates'),)/myapp/index.html (File does not exist)
What am I doing wrong?
Finally solved this problem!
Need to edit TEMPLATES' 'DIRS' string in settings.py to:
'DIRS': (BASE_DIR.child('templates'),),

Categories

Resources