I was having issues with print statements and Django and I saw on here that its better to do logging. I am not sure what I am doing wrong though. It logs sometimes to console and other times it doesn't for the same page and I cant get it to log anything in my post method.
I have tried doing the logger = logging.getLogger("mylogger") above all the class views, ive tried adding that line to each individual method and ive tried only having it in 1 at a time. Any thoughts?
Settings.py
"""
Django settings for caspers_trading_tools project.
Generated by 'django-admin startproject' using Django 4.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-d^#mw27((%t$wzj+3eykdmfmweufzep44sgkhib)^n1thdh!y6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'landing_page',
'trading_log',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'caspers_trading_tools.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR / "templates",
BASE_DIR / "templates" / "includes"
],
'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',
],
},
},
]
WSGI_APPLICATION = 'caspers_trading_tools.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
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/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / "static"
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'filters': ['require_debug_true'],
},
},
'loggers': {
'mylogger': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
'propagate': True,
},
},
}
Views.py
class CreateOrderView(View):
def get(self, request,):
logger = logging.getLogger("mylogger")
logger.info("TEST")
# this should be removed once user_ids are implemented through login system and session creation
request.session["user_id"] = 1
# should be set to session.get("user_id") probably in the future
user_id = request.session.get("user_id")
trade_form = CreateTradeForm()
order_form = CreateOrderForm()
context = {}
context["user_id"] = user_id
context["order_form"] = order_form
context["trade_form"] = trade_form
return render(request, "trading_log/add-order.html", context)
def post(self, request):
trade_form = CreateTradeView(request.POST)
order_form = CreateOrderForm(request.POST)
trade = trade_form.save(commit=False)
order = order_form.save(commit=False)
logger = logging.getLogger("mylogger")
logger.info("TEST")
# logger.info("TRADE", trade)
# logger.info("ORDER", order)
return HttpResponseRedirect(reverse("add-order-page"))
If you need any other files please let me know. I dont think ive done anything anywhere to make logging work.
I see that you're using the RequireDebugTrue filter, which means that you will only get logs printed if DEBUG is set to True in your settings file (which you do not show in your post).
Additionally, you do not need to set the logger variable in every single method. It's ok to declare it once per module globally.
Related
I have the exact same code deployed locally on development server and Linode Virtual Private Server. The Local site works fine, but when I try to access the same url on the VPS, I see this in the browser:
This site can’t be reached XXX.XXX.XXX.X refused to connect.
Try:
Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED
Even when I go to the admin site it is broken.
I have narrowed the change down to my views.py and settings.py file changes, as I was making one code change at a time to try and find out where the VPS did not like my code. I am unable to understand why the Django App just seems to break.
My views.py function, the last line of code will be called:
def start_or_end_fast(request):
if request.method == 'POST' and 'start_fast' in request.POST:
start()
return HttpResponseRedirect(reverse('start_or_end_fast'))
elif request.method == 'POST' and 'end_fast' in request.POST:
print('mmmmm')
end()
return HttpResponseRedirect(reverse('start_or_end_fast'))
elif request.method == 'POST' and 'duration' in request.POST:
duration = time_difference()
return render(request,'startandstoptimes/index.html', {'duration': duration})
else:
return render(request,'startandstoptimes/index.html')
settings.py:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXX'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#Xs to mask IP on Stackoverflow
ALLOWED_HOSTS = ['XXX.XXX.XXX.XXX.X','127.0.0.1']
# Application definition
INSTALLED_APPS = [
'startandstoptimes.apps.StartandstoptimesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'DjangoApp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(SETTINGS_PATH, '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',
],
},
},
]
WSGI_APPLICATION = 'DjangoApp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
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/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
I am thinking there may be some configuration on my server on something that needs changed, I am stumped.
I am making a Django authentication program but keeps on giving me this error.
django.template.exceptions.TemplateDoesNotExist: templates/index.html Error.
PLS help me coz I have spent hours trying to solve this problem.
Views.py
from django.http import HttpResponse
def home(request):
return render(request, "authentication/index.html")
def signin(request):
return render(request, "authentication/signin.html")
def signout(request):
pass
Urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('',views.home, name = "home"),
path('signin',views.signin, name = "signin"),
path('signout',views.signout, name = "signout"),
]
Settings
"""
Django settings for gfg project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-tqa6(3cnb_f#3u(56)mu9z%d2c548xypd-#%6i&60#)mxbs$k'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'gfg.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'gfg.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
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/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
authentication is my app folder while gfg is my start project.
from what i can see in your code. you have to create a folder "templates" in the root of your project directory. you also have to create an "authentication" folder in the templates folder and place index.html in the authentication folder. it will work.
I have a telegram bot witch depends on a Django app, I'm trying to deploy it on Heroku but I get this error
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
when it runs python3 main/bot.py in Heroku
here is my Procfile:
web: gunicorn telega.wsgi
worker: python main/bot.py
main/bot.py:
import telebot
import traceback
from decimal import Decimal, ROUND_FLOOR
import requests
import json
from django.conf import settings
from preferences import preferences
from main.markups import *
from main.tools import *
config = preferences.Config
TOKEN = config.bot_token
from main.models import *
from telebot.types import LabeledPrice
# # #
if settings.DEBUG:
TOKEN = 'mybottoken'
# # #
bot = telebot.TeleBot(TOKEN)
admins = config.admin_list.split('\n')
admin_list = list(map(int, admins))
#bot.message_handler(commands=['start'])
def start(message):
user = get_user(message)
lang = preferences.Language
clear_user(user)
if user.user_id in admin_list:
bot.send_message(user.user_id,
text=clear_text(lang.start_greetings_message),
reply_markup=main_admin_markup(),
parse_mode='html')
else:
bot.send_message(user.user_id,
text=clear_text(lang.start_greetings_message),
reply_markup=main_menu_markup(),
parse_mode='html')
#bot.message_handler(func=lambda message: message.text == preferences.Language.porfolio_button)
def porfolio_button(message):
....
...
and my settings.py:
"""
Django settings for telega project.
Generated by 'django-admin startproject' using Django 2.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import django_heroku
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'sw)pfb7&!l98xdoxn9(hy4eacwm33tj1vknyhz#tmv3mr-#ueo'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost',
"https://olk-telegram-bot.herokuapp.com"
"olk-telegram-bot.herokuapp.com",
"www.olk-telegram-bot.herokuapp.com",
"olk-telegram-bot"
".herokuapp.com",
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'preferences',
'main',
'ckeditor',
'dbbackup', # django-dbbackup
]
DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage'
DBBACKUP_STORAGE_OPTIONS = {'location': os.path.join(BASE_DIR, "backup")}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'telega.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'telega.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'CONN_MAX_AGE': 3600,
'NAME': 'portfolio',
'USER': 'mysql',
'HOST': 'localhost',
'PORT': '3306',
'PASSWORD': 'mysql',
'OPTIONS': {
'charset': 'utf8mb4',
},
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static"),
# ]
CKEDITOR_CONFIGS = {
'default': {
'enterMode': 2,
'linkShowAdvancedTab': False,
'linkShowTargetTab': False,
'toolbar': 'Custom',
'toolbar_Custom': [
['Bold', 'Italic', 'Underline'],
['Link', 'Unlink'],
['RemoveFormat', 'Source']
],
}
}
# Activate Django-Heroku.
django_heroku.settings(locals())
del DATABASES['default']['OPTIONS']['sslmode']
SITE_ID = 2
I don't know if I'm doing right or no, it'll be appreciated if you guide me through :)
In settings.py under INSTALLED_APPS you need to do app_name.apps.AppNameConfig.
So if you app name was telegram_bot you would do telegram_bot.apps.TelegramBotConfig.
Turns out I should run polling.py not main/bot.py -__-
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',
},
}
}
Problem: template not loading with view ....
I've been following a django tutorial, hoping to get some templates working that I created. It looks like this.
app/templates
└── app
└── profile.html
Settings file looks like this:
"""
Django settings for demonstration project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
# 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 = 'SOME_KEY_NON_PROD_TESTING_LOCALLY'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'demonstration.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'demonstration.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
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 = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
The tutorial mentioned defining a template dir so I defined:
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
However, that didn't work so I also saw the DIRs option in the template stanza to I set that to the same value as TEMPLATE_DIRS that I added above.
I still don't see any change here. I am obviously missing something about the config that should point to the template but I'm stumped as to what that is at the moment.
The view:
from django.shortcuts import render, HttpResponse
import requests
import json
# Create your views here.
def index(request):
return HttpResponse('Hello World!')
def second_view(request):
return HttpResponse('This is the second view!')
def profile(request):
jsonList = []
req = requests.get('https://api.github.com/users/<username_here>')
jsonList.append(json.loads(req.content.decode()))
parsedData = []
userData = {}
for data in jsonList:
userData['name'] = data['name']
userData['email'] = data['email']
userData['public_gists'] = data['public_gists']
userData['public_repos'] = data['public_repos']
userData['avatar_url'] = data['avatar_url']
userData['followers'] = data['followers']
userData['following'] = data['following']
parsedData.append(userData)
return HttpResponse(parsedData)
The page source of localhost:8000/app/profile
{'followers': 1, 'public_repos': 5, 'avatar_url': 'https://avatars.githubusercontent.com/u/XXXXX', 'email': None, 'following': 4, 'name': None, 'public_gists': 1}
If your templates folder is in your project root folder and you have profile.html like this:
templates/app/profile.html then your view should be something like:
def some_view(request)
# some code
return render(request, 'app/profile.html')
Your profile view could be:
def profile(request)
# your code
return render(request, 'app/profile.html', {'data': userData})
Now, in your template profile.html, you can access the object data
Need to return render to view e.g. return render(request, 'app/profile.html', {'data': parsedData})