I recently tried to implement a custom view for my 404 and 500 errors on my website. It works well when debug is set to True, i.e. both the custom views work well when called. But as soon as set my Debug to False only the error 500 will be raised
I tried already to call them by creating a url, both of the handler404 and handler500 custom view works well.
This is the view where it should raise an error 404 when badly called:
def arret(request, id):
""" Page that show an textuel """
view = 'search/arret.html'
arret = get_object_or_404(Arret, id=id)
arret.compute_bgeref_id()
query = request.GET.get('q', '')
form_class = DecisionForm()
title = arret.highlight_words(query,input_text=arret.title)
text = arret.highlight_words(query)
arret_judges = arret.arret_judges.all()
decision = arret.decision
return render(request, view, {'title': title,'text': text, 'date':arret.date, 'tag_string': arret.tag_string, 'tags': arret.get_n_tags(), 'articles': arret.get_n_law_articles(n=15),
'bgeref_id': arret.bgeref_ids.all(),"form": form_class, 'id':id, 'query' : query, 'decision': decision,'arret_judges':arret_judges, 'ATF':arret.source=='ATF'
})
Here you can find my 404 custom view:
def handler404(request, template_name="colorlib-error-404-19/index.html"):
response = render_to_response("colorlib-error-404-19/index.html")
response.status_code = 404
return response
it raises an error 500 when trying to find a non existing Arret. this is what is written in the terminal
System check identified no issues (0 silenced).
June 22, 2019 - 08:55:31
Django version 2.0, using settings 'nora.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[22/Jun/2019 08:55:32] "GET /arret/100/?q=loi HTTP/1.1" 500 1435
Edit: add settings file
Here is my settings_file:
import os
from django.utils.translation import gettext_lazy as _
from requests_aws4auth import AWS4Auth
import elasticsearch
user = os.getenv('USER')
# 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/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 = True
if user == 'user':
DEBUG = False
else:
DEBUG = True
# ALLOWED_HOSTS
if user == 'user': # Checks if the settings is on the website
ALLOWED_HOSTS = [ '.neuralen.ch', '.mstamenk.webfactional.com' ]
else :
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'haystack',
'search',
'authUser',
'debug_toolbar',
'haystack_panel',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'nora.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',
"django.template.context_processors.i18n",
],
},
},
]
#TEMPLATE_DIRS = ( failed attempt
# os.path.join(BASE_DIR, 'templates'),
#)
WSGI_APPLICATION = 'nora.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
if user == 'user': # Check if settings.py is on website server
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'nora_db',
'USER': 'neuralen',
'PASSWORD': #################,
'HOST': '127.0.0.1',
'PORT': '5432',
},
'nora_db_2': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'nora_db_2',
'USER': 'neuralen',
'PASSWORD': '################',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
else: # Otherwise, it's in local
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'nora_db_2': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'second_db.sqlite3'),
},
}
#DATABASE_ROUTERS = ['search.routers.SearchRouter']
# AWS
AACCESS_KEY = ##########################
SECRET_KEY = ##########################
REGION = 'us-east-1'
AWSHOST = 'https://search-nora-y6ko4vsxcd4255tcs4gznzbaou.us-east-1.es.amazonaws.com'
awsauth = AWS4Auth(AACCESS_KEY,SECRET_KEY,REGION,'es')
# Haystack connection to elasticsearch.
#https://stackoverflow.com/questions/35090762/django-haystack-using-amazon-elasticsearch-hosting-with-iam-credentials?rq=1
HAYSTACK_CUSTOM_HIGHLIGHTER ="nora.utils.nora_Highlighter"
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack_es.backends.Elasticsearch5SearchEngine',
#'URL': 'http://127.0.0.1:9200/',
'URL': AWSHOST,
'INDEX_NAME': 'nora',
'INCLUDE_SPELLING' : True,
'KWARGS': {
'port': 443,
'http_auth': awsauth,
'use_ssl': True,
'verify_certs': True,
'connection_class': elasticsearch.RequestsHttpConnection,
}
},
}
if user == 'user':
HAYSTACK_CONNECTIONS['default']['INDEX_NAME'] = 'nora-server'
else:
HAYSTACK_CONNECTIONS['default']['INDEX_NAME'] = 'nora'
# 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'
#LANGUAGE_CODE = 'fr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
gettext = lambda x: x
LANGUAGES = (
('en', _('English')),
('fr', _('French')),
('de', _('German')),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
if user == 'user': # Check if on website
STATIC_URL = 'https://neuralen.ch/django_nora_static/'
else: # Otherwise running in local
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static/"),
)
if user == 'user':
STATIC_ROOT = '/home/user/webapps/django_nora_static/'
else:
STATIC_ROOT = os.path.join(BASE_DIR, "static_root/")
# Authentification
LOGIN_URL = 'accounts/login'
LOGIN_REDIRECT_URL = '/'
#SMTP Email Serivce
#https://simpleisbetterthancomplex.com/tutorial/2016/06/13/how-to-send-email.html
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'testsite_app'
EMAIL_HOST_PASSWORD = '################'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'TestSite Team <noreply@example.com>'
#EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # During development only
INTERNAL_IPS = [ '127.0.0.1']
DEBUG_TOOLBAR_PANELS = [
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
'haystack_panel.panel.HaystackDebugPanel',
]