"GET / HTTP/1.1" 500 145 - django

Anytime I turn debug to false in my settings.py my site gives a server error. This is what my server shows and the site doesn't work again but when debug is true it works perfectly, I don't know what's wrong anyone with ideas on what might be going wrong
Performing system checks...
System check identified no issues (0 silenced).
October 21, 2022 - 23:47:07
Django version 4.1.2, using settings 'dlcfogbomoso.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[21/Oct/2022 23:47:09] "GET / HTTP/1.1" 500 145
[21/Oct/2022 23:54:18] "GET / HTTP/1.1" 500 145
This is my settings.py file check it out for any error(s):
from pathlib import Path
import os
from decouple import config
from django.core.management.utils import get_random_secret_key
# 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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "Django-insecure-)=l1an%f&lb0+7z#!5l!ang_l!76ahs4eb-$((lt7vo1-mv0(*"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"whitenoise.runserver_nostatic",
"django.contrib.staticfiles",
"myapp",
]
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.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "dlcfogbomoso.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [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 = "dlcfogbomoso.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "dlcfogbomoso",
"USER": "postgres",
"PASSWORD": "admin",
"HOST": "localhost"
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.1/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.1/howto/static-files/
STATIC_URL = "/static/"
MEDIA_ROOT = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Please what am I doing wrong?

Not a definitive answer, but help. too long for comment
Go into your settings.py and add the code block below. This overrides the default Logging settings to output errors to the console even when debug is set as False. If you already have a LOGGING dict in the settings, just comment it out
Note: defaults are commented out, I just disabled the filters & disabled the existing default loggers
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
# 'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'formatters': {
'django.server': {
'()': 'django.utils.log.ServerFormatter',
'format': '[{server_time}] {message}',
'style': '{',
}
},
'handlers': {
'console': {
'level': 'INFO',
#'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
},
'django.server': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'django.server',
},
'mail_admins': {
'level': 'ERROR',
#'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django': {
'handlers': ['console', 'mail_admins'],
'level': 'INFO',
},
'django.server': {
'handlers': ['django.server'],
'level': 'INFO',
'propagate': False,
},
}
}

Related

Django/Heroku deployment problems: Won't work on Debug = False

I got my app to deploy, but pages that require an id in session are not rendering. When I set debug = true, everything works fine. Otherwise, I get error 500 message. I've tried many different solutions to no avail.
I imagine the problem is somewhere in my settings.py so I have included that below. I was also able to log the startup so that is included as well.
The main page and pages that don't get a request.session passed into them work fine, as well as functions that update the database. Only pages that require an id passed into the path are not working.
update:
I ran the logentries extension for heroku and found an error on this line:
File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 420, in stored_name
raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name)
ValueError: Missing staticfiles manifest entry for '/css/bootstrap.min.css'
I still don't know what to do
import dj_database_url
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'wiki_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.postgres',
]
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'coding_dojo_final_project.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',
],
},
},
]
WSGI_APPLICATION = 'coding_dojo_final_project.wsgi.application'
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': '***',
'HOST': 'localhost',
'PORT': '****',
}
}
WHITENOISE_USE_FINDERS = True
...
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': ('%(asctime)s [%(process)d] [%(levelname)s] '
'pathname=%(pathname)s lineno=%(lineno)s '
'funcname=%(funcName)s %(message)s'),
'datefmt': '%Y-%m-%d %H:%M:%S'
},
'simple': {
'format': '%(levelname)s %(message)s'
}
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
'django.request': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
}
}
STATIC_URL = '/static/'
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
not exactly sure, but something went wrong when I compiled all my static filed. I had to...
+ STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
- STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

Customized PasswordResetSerializer and now it's throwing error 500

I am contributing to an open-source org where they are using django-rest-auth for authentication purposes. I have to simply override the email template for a password reset. So I used imported PasswordResetSerializer and then customized it. It worked in the first place but when I restarted the whole environment it stopped working and just showed this in terminal
django_1 | [pid: 65|app: 0|req: 1/1] 172.19.0.1 () {42 vars in 696 bytes} [Thu Jan 7 22:06:59 2021] OPTIONS /api/auth/password/reset/ => generated 0 bytes in 4 msecs (HTTP/1.1 200) 7 headers in 365 bytes (1 switches on core 0)
django_1 | [pid: 67|app: 0|req: 1/2] 172.19.0.1 () {42 vars in 696 bytes} [Thu Jan 7 22:06:59 2021] POST /api/auth/password/reset/ => generated 22264 bytes in 796 msecs (HTTP/1.1 500) 5 headers in 177 bytes (1 switches on core 0)
It's showing me error 500.
I tried to use debugger but here the all environment is setup using docker and I couldn't figure out what's going wrong.
Here are the files
settings.py
"""
Django settings for evalai project.
Generated by 'django-admin startproject' using Django 1.10.2.
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 datetime
import os
import sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
APPS_DIR = os.path.join(BASE_DIR, "apps")
sys.path.append(APPS_DIR)
# 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 = os.environ.get("SECRET_KEY", "random_secret_key")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEST = False
ALLOWED_HOSTS = []
EVALAI_API_SERVER = os.environ.get("EVALAI_API_SERVER", "http://localhost:8000")
# Application definition
DEFAULT_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django.contrib.sites",
]
OUR_APPS = [
"accounts",
"analytics",
"base",
"challenges",
"hosts",
"jobs",
"participants",
"web",
]
THIRD_PARTY_APPS = [
"allauth",
"allauth.account",
'allauth.socialaccount',
"corsheaders",
"django_ses",
"import_export",
"rest_auth",
"rest_auth.registration",
"rest_framework.authtoken",
"rest_framework",
"rest_framework_expiring_authtoken",
"drf_yasg",
"django_filters",
]
INSTALLED_APPS = DEFAULT_APPS + OUR_APPS + THIRD_PARTY_APPS
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"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 = "evalai.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",
]
},
}
]
WSGI_APPLICATION = "evalai.wsgi.application"
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" # noqa
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator" # noqa
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator" # noqa
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator" # noqa
},
]
# 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/"
STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
SITE_ID = 1
REST_FRAMEWORK = {
"DEFAULT_PAGINATION_CLASS": (
"rest_framework.pagination.LimitOffsetPagination"
),
"PAGE_SIZE": 100,
"TEAM_PAGE_SIZE": 10,
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticatedOrReadOnly"
],
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework_expiring_authtoken.authentication.ExpiringTokenAuthentication"
],
"TEST_REQUEST_DEFAULT_FORMAT": "json",
"DEFAULT_THROTTLE_CLASSES": (
"rest_framework.throttling.AnonRateThrottle",
"rest_framework.throttling.UserRateThrottle",
),
"DEFAULT_THROTTLE_RATES": {
"anon": "100/minute",
"user": "100/minute",
"resend_email": "3/hour",
},
"DEFAULT_RENDERER_CLASSES": ("rest_framework.renderers.JSONRenderer",),
}
# ALLAUTH SETTINGS
ACCOUNT_EMAIL_REQUIRED = True
OLD_PASSWORD_FIELD_ENABLED = True
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = (
"/api/auth/email-confirmed/"
)
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = (
"/api/auth/email-confirmed/"
)
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME")
AWS_ACCOUNT_ID = os.environ.get("AWS_ACCOUNT_ID", "aws_account_id")
AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID", "aws_access_key_id")
AWS_SECRET_ACCESS_KEY = os.environ.get(
"AWS_SECRET_ACCESS_KEY", "aws_secret_access_key"
)
AWS_REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")
# Broker url for celery
CELERY_BROKER_URL = "sqs://%s:%s#" % (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
# CORS Settings
CORS_ORIGIN_ALLOW_ALL = True
# REST Framework Expiring Tokens Configuration
EXPIRING_TOKEN_LIFESPAN = datetime.timedelta(days=365)
# Logging
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"root": {"level": "INFO", "handlers": ["console"]},
"filters": {
"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"},
"require_debug_true": {"()": "django.utils.log.RequireDebugTrue"},
},
"formatters": {
"simple": {
"format": "[%(asctime)s] %(levelname)s %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
},
"verbose": {
"format": "[%(asctime)s] %(levelname)s %(module)s %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
},
},
"handlers": {
"console": {
"level": "INFO",
"filters": ["require_debug_true"],
"class": "logging.StreamHandler",
"formatter": "simple",
},
"logfile": {
"level": "DEBUG",
"class": "logging.handlers.RotatingFileHandler",
"filename": os.path.join(BASE_DIR, "django.log"),
"maxBytes": 50000,
"backupCount": 10,
"formatter": "verbose",
},
"mail_admins": {
"level": "ERROR",
"class": "django.utils.log.AdminEmailHandler",
"filters": ["require_debug_false"],
},
},
"loggers": {
"django": {"handlers": ["console"], "propagate": False},
"django.request": {
"handlers": ["mail_admins"],
"level": "ERROR",
"propagate": False,
},
"django.security": {
"handlers": ["mail_admins"],
"level": "ERROR",
"propagate": False,
},
"django.db.backends": {
"handlers": ["mail_admins"],
"level": "ERROR",
"propagate": False,
},
},
}
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.memcached.MemcachedCache"
}
}
# The maximum size in bytes for request body
# https://docs.djangoproject.com/en/1.10/ref/settings/#data-upload-max-memory-size
FILE_UPLOAD_MAX_MEMORY_SIZE = 4294967296 # 4 GB
DATA_UPLOAD_MAX_MEMORY_SIZE = 4294967296 # 4 GB
# To make usermame field read-only, customized serializer is defined.
REST_AUTH_SERIALIZERS = {
"USER_DETAILS_SERIALIZER": "accounts.serializers.ProfileSerializer",
"PASSWORD_RESET_SERIALIZER": "accounts.serializers.CustomPasswordResetSerializer"
}
# For inviting users to participant and host teams.
ADMIN_EMAIL = "admin#cloudcv.org"
CLOUDCV_TEAM_EMAIL = "EvalAI Team <team#cloudcv.org>"
# Expiry time of a presigned url for uploading files to AWS, in seconds.
PRESIGNED_URL_EXPIRY_TIME = 3600
# Slack web hook url
SLACK_WEB_HOOK_URL = os.environ.get(
"SLACK_WEB_HOOK_URL", "http://testslackwebhook.com/webhook"
)
SWAGGER_SETTINGS = {
"DEFAULT_INFO": "evalai.urls.swagger_api_info",
"SECURITY_DEFINITIONS": {
"Token Authentication": {
"type": "apiKey",
"name": "Authorization",
"in": "header",
}
},
}
REDOC_SETTINGS = {"SPEC_URL": ("docs.yaml", {"format": ".yaml"})}
DJANGO_SERVER = os.environ.get("DJANGO_SERVER")
DJANGO_SERVER_PORT = os.environ.get("DJANGO_SERVER_PORT")
HOSTNAME = os.environ.get("HOSTNAME")
SENDGRID_SETTINGS = {
"TEMPLATES": {
"CHALLENGE_INVITATION": "d-60825bcf014f4958bdb1b9173471d420",
"CHALLENGE_APPROVAL_EMAIL": "d-45e0adc0597b4b60bd7c384aa903c488",
"WORKER_RESTART_EMAIL": "d-3d9a474a5e2b4ac4ad5a45ba9c0b84bd",
"CLUSTER_CREATION_TEMPLATE": "d-6de90fd760df4a41bb9bff1872eaab82",
"WORKER_START_EMAIL": "d-debd127cab2345e789538131501ff416",
}
}
# EKS configs for Rl-worker
EKS_CLUSTER_ROLE_ARN = os.environ.get("EKS_CLUSTER_ROLE_ARN")
EKS_NODEGROUP_ROLE_ARN = os.environ.get("EKS_NODEGROUP_ROLE_ARN")
ENVIRONMENT = os.environ.get("ENVIRONMENT", "dev")
serializers.py
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_auth.serializers import PasswordResetSerializer
class UserDetailsSerializer(serializers.ModelSerializer):
"""
Make username as a read_only field.
"""
class Meta:
model = get_user_model()
fields = (
"pk",
"email",
"username",
"first_name",
"last_name",
"password",
)
read_only_fields = ("email", "username")
class ProfileSerializer(UserDetailsSerializer):
"""
Serializer to update the user profile.
"""
affiliation = serializers.CharField(source="profile.affiliation")
github_url = serializers.URLField(
source="profile.github_url", allow_blank=True
)
google_scholar_url = serializers.URLField(
source="profile.google_scholar_url", allow_blank=True
)
linkedin_url = serializers.URLField(
source="profile.linkedin_url", allow_blank=True
)
class Meta(UserDetailsSerializer.Meta):
fields = (
"pk",
"email",
"username",
"first_name",
"last_name",
"affiliation",
"github_url",
"google_scholar_url",
"linkedin_url",
)
def update(self, instance, validated_data):
profile_data = validated_data.pop("profile", {})
affiliation = profile_data.get("affiliation")
github_url = profile_data.get("github_url")
google_scholar_url = profile_data.get("google_scholar_url")
linkedin_url = profile_data.get("linkedin_url")
instance = super(ProfileSerializer, self).update(
instance, validated_data
)
profile = instance.profile
if profile_data and affiliation:
profile.affiliation = affiliation
profile.github_url = github_url
profile.google_scholar_url = google_scholar_url
profile.linkedin_url = linkedin_url
profile.save()
return instance
class CustomPasswordResetSerializer(PasswordResetSerializer):
def get_email_options(self):
super().get_email_options()
return {
'subject_template_name': 'account/email/password_reset_key_subject.txt',
'email_template_name': 'account/password_reset_email.html',
'html_email_template_name': 'account/password_reset_email.html',
}
I've been stuck to this issue for about 1 week and I'm losing my confidence.
open source project is here, incase you want to check.
UPDATE - Now I'm getting another problem in which my email looks like this, I'm not getting the variable passed here.
enter image description here
And it should look like this
enter image description here
password_reset_email.html
{% load i18n %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Hello from {{ site_name }}!
You're receiving this e-mail because you or someone else has requested a password for your user account at {{ site_domain }}.
It can be safely ignored if you did not request a password reset. Click the link below to reset your password.{% endblocktrans %}
{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
{% if username %}{% blocktrans %}In case you forgot, your username is {{ username }}.{% endblocktrans %}
{% endif %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Thank you for using {{ site_name }}!
{{ site_domain }}{% endblocktrans %}
UPDATE - I solved this issue by changing the extension from html to txt. It's strange I know but worked for me.
I was able to solve this answer by simply putting this logging code to settings.py file.
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
},
'handlers': {
'console': {
'level': 'NOTSET',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'': {
'handlers': ['console'],
'level': 'NOTSET',
},
'django.request': {
'handlers': ['console'],
'propagate': False,
'level': 'ERROR'
}
}
}
The org in which I was contributing they were using docker file to setup the environment and they have edited the logging file according to them.
By adding that code to the settings file I was able to receive the error logs.

Django debug False prevents access to files saved in media folder

I have a model that takes a File Field which is uploaded in Django admin. I noticed that the files save in the proper folder. But when Debug is set to False, I cannot access the file from the admin area or from the front end user interface. I get an error message that says "The resource could not be found on the server."
The app is hosted on Heroku and does the same thing in localhost and live. I read in another post that Whitenoise would work with Heroku but it hasn't resolved the issue. Could someone please point me in the right direction to a fix? The relevant files are below.
Update: Adding urls.py
urls.py
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings
from .views import DatasetListView
from django.conf import settings
import pages.views
urlpatterns = [
path('', include('pages.urls')),
path('users/', include('users.urls')),
path('accounts/', include('allauth.urls')),
path('admin/', admin.site.urls),
path('downloads/', views.DatasetListView.as_view(), name='downloads'), # where users download the files
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
models.py
from django.core.files.storage import FileSystemStorage
from django.db import models
class DataSet(models.Model):
title = models.CharField(max_length=255)
date_added = models.DateField(auto_now=True)
file_size = models.CharField(max_length=20)
file_type = models.CharField(max_length=20)
data_file = models.FileField(upload_to='delivery/')
def __str__(self):
return self.title
settings.py
import os
import django_heroku
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = Redacted
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
DEBUG_PROPAGATE_EXCEPTIONS = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'django.contrib.sites',
# third-party apps
'anymail',
# project apps
'pages',
'users',
'allauth',
'allauth.account',
'allauth.socialaccount',
]
AUTH_USER_MODEL = Redacted
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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myapp.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.media',
],
},
},
]
WSGI_APPLICATION = 'myapp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'Redacted',
'USER': 'Redacted',
'PASSWORD': 'Redacted',
'HOST': '/Redacted',
'PORT': 'Redacted'
}
}
# 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, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
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',
},
}
}
# Configure Django App for Heroku.
django_heroku.settings(locals())
Thanks for your help.

How exactly configure Django to send emails with bug reports?

I am really novice with Django, and I am having troubles in configuring my app to send me emails with the bug reports.
I already set on the settings file the required variables as I saw on the Django documentation, like this:
DEBUG = False
...
ADMINS = [('myname', 'myemail#server')] # For server errors
MANAGERS = [('myname', 'myemail#server')] # For missing pages errors
I provoked a error for testing, but nothing happened, no email. What should I do?
This is the code of the settings file (without sensitive data, of course):
"""
Django settings for genform project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = '****************************************'
DEBUG = False
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'widget_tweaks',
'generador',
'menu',
'parametros_transformados',
'seguridad',
'tablas_de_no_parametros',
'reportes',
'logger',
'parametros',
'django_openid_auth'
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
AUTHENTICATION_BACKENDS = (
'django_openid_auth.auth.OpenIDBackend',
'django.contrib.auth.backends.ModelBackend',
)
TEMPLATES = [
{
'BACKEND':'django.template.backends.django.DjangoTemplates',
'DIRS':[os.path.join(os.path.dirname(__file__), '../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',
],
},
},
]
OPENID_UPDATE_DETAILS_FROM_SREG = True
ROOT_URLCONF = 'genform.urls'
WSGI_APPLICATION = 'genform.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '*****',
'USER': '******',
'PASSWORD': '******',
'HOST': '***********',
'PORT': '***',
}
}
STATICFILES_DIRS = (
#os.path.dirname(__file__)+"static",
# Put strings here, like "/home/html/site_media" or "C:/www/django/site_media".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.path.dirname(__file__), '../static'),
)
AUTH_PROFILE_MODULE = 'seguridad.c_perfil_usuario'
LOGIN_REDIRECT_URL = '/index'
OPENID_SSO_SERVER_URL = '***********'
OPENID_CREATE_USERS = True
LANGUAGE_CODE = 'es-es'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
ADMINS = [('MyName', 'myemail#server')]
MANAGERS = [('MyName', 'myemail#server')]
What's your LOGGING configuration?
I use the following in my production environment:
ADMINS = [
('Admin1', 'admin1#mail.com'),
('Admin2', 'admin2#mail.com')
]
MANAGERS = ADMINS
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # for testing
EMAIL_HOST = 'relay.server.com'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s '
'%(process)d %(thread)d %(message)s'
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false', ],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins', ],
'level': 'ERROR',
'propagate': True
},
'django.security.DisallowedHost': {
'level': 'ERROR',
'handlers': ['console', 'mail_admins', ],
'propagate': True
}
}
}
Make sure you have a valid EMAIL_BACKEND defined. You can use a service like mailgun or even gmail if you don't have a own SMTP server (EMAIL_HOST).
Thoese settings look correct, but there are other things that may be holding you up.
Email info in settings.py may not be configured
You have overwritten the default log settings in settings.py and are not writing errors to the email log.
If one or both of these are not setup correctly, then you won't get the emails.
To fix 1 you can look at this answer: https://stackoverflow.com/a/4642194/4788717
To fix 2, you can check out the docs: https://docs.djangoproject.com/en/dev/topics/logging/ and make sure you have either the default or mail admins case:
LOGGING = {
...
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['special']
...
}

Css and Javascripts not loading on login page in Django?

Here is my settings file.. I am getting the login page but the css and javascripts are not loading.
I gotthe whole project and i have to start working on it but i only know the basic of django so not sure why css and javascripts arenot loading. this is a very old project so it is using python 2.6.5 and django 1.3. the folder structure is also old.
# Django settings for athena.
import socket
# determine whether it's prod or dev or test/uat
if socket.gethostname().split('.')[0].lower().strip() in ('athena-dev', 'athena-test', 'lucid32'):
ATHENA_PROD_MODE = False
elif socket.gethostname().split('.')[0].lower().strip() == 'athena':
ATHENA_PROD_MODE = True
else:
raise Exception('cannot determine what mode (prod or dev) to operate in')
ATHENA_UAT_MODE = (socket.gethostname().split('.')[0].lower().strip() == 'athena-test')
if ATHENA_PROD_MODE:
DEBUG = False
else:
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (('PASystemSupport', 'pasystemsupport#apa.org'), )
MANAGERS = ADMINS
if ATHENA_PROD_MODE:
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'Athena',
'USER': 'ftdbuser',
'PASSWORD': 'f0lt5xt',
'HOST': 'PIDB-SQL',
'OPTIONS': {
'driver': 'SQL Server',
'autocommit': True,
'dsn': 'PIDB-SQL',
'use_mars': True
}
}
}
elif ATHENA_UAT_MODE:
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'Athena-UAT',
'USER': 'ftdbuser',
'PASSWORD': 'f0lt5xt',
'HOST': 'LANDB-DEV',
'OPTIONS': {
'driver': 'SQL Server',
'autocommit': True,
'dsn': 'LANDB-DEV',
'use_mars': True
}
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/vagrant/Athena/athena_root/athena.db',
}
}
# 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.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/New_York'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/vagrant/Athena/athena_root/athena_static/'
# 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 = '/athena_static/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '7*f!l)^v!81vog#yzd23scp5+30db=)bub(j88nz!37nnt62mh'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'athena_root.athena.middleware.ApplyAuthentication',
'athena_root.athena.workflow.middleware.ProdViewPermissions'
)
ROOT_URLCONF = 'athena_root.athena.urls'
TEMPLATE_DIRS = ('/vagrant/Athena/athena_root/athena_templates',
'/vagrant/Athena/athena_root/ltt/templates',
'/vagrant/Athena/athena_root/errata/templates')
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.contrib.messages.context_processors.messages",
"athena_root.athena.template_context_proc.baseTemplateContext"
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.humanize',
'athena_root.athena',
'athena_root.ltt',
'athena_root.errata'
)
EMAIL_HOST = 'mailhost.apa.org'
SERVER_EMAIL = 'PASystemsupport#apa.org'
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'django.utils.log.NullHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True
},
'aem_db_logger': {
'level': 'DEBUG',
'class': 'athena_root.errata.log.DatabaseLoggingHandler',
'formatter': 'verbose'
}
},
'loggers': {
'django': {
'handlers': ['null'],
'propagate': True,
'level': 'INFO',
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': False,
},
'athena_root.errata': {
'handlers': ['aem_db_logger'],
'level': 'DEBUG',
'propagate': True
}
}
}
AUTHENTICATION_BACKENDS = ('athena_root.athena.auth.backends.AthenaAuthBackend',)
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/login'
LOGOUT_URL = '/logout'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_COOKIE_AGE = 7257600
SESSION_SAVE_EVERY_REQUEST = False
`