Django TemplateView raising on production Server 500 error
I am using Django with a gunicorn server for serving the dynamic templates and also the static files with whitenoise.
The application runs in an Docker-Container with a postgresql Database.
When using the DEBUG = True in the setting files. The html using TemplateView class is displayed.
However, when changing to DEBUG = FALSE the server raises a 500 code. All the other pages are rendered and work. So I dont think it is an issue where I placed the html files.
Also the static files are beeing served by gunicorn correctly.
What I found out so far is that in the settings:
#STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Makes the difference...but how and why?
I was aked to create a MRE. So here it is and I hope it is fine like this.
To reproduce it the following is needed: a django project and docker.
In the settings I have a base.py and a test.py.
Here the base.py
"""
Django settings for RootApplication project.
Generated by 'django-admin startproject' using Django 2.1.dev20180114011155.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import os
from django.utils.translation import gettext_lazy as _
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
print("BASE_DIR:", BASE_DIR)
DEBUG = False
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Application definition
INSTALLED_APPS = [
# Django core apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-party apps
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
#'pwa', # Uncomment if you're using these
#'webpush',
# Custom apps
'landing_page.apps.Landing_PageConfig',
'api.apps.ApiConfig',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'RootApplication.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 = 'RootApplication.wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/dev/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/dev/topics/i18n/
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'api', 'locale'),
os.path.join(BASE_DIR, 'landing_page', 'locale'),
]
LANGUAGE_CODE = 'en'
LANGUAGES = (
('de', _('German')),
('en', _('English')),
)
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = '/static/'
if not DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Tell Django to use WhiteNoise to serve static files
#STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
if DEBUG:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
#'firebase.authentication.FirebaseAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
#'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.AllowAny',
],
}
Here is the extension of the base.py with a test.py
"""
Django settings for RootApplication2 project.
Generated by 'django-admin startproject' using Django 2.1.dev20180114011155.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import os
from .base import *
from django.utils.translation import gettext_lazy as _
# Add production-specific apps
INSTALLED_APPS += [
]
# Add production-specific middleware
MIDDLEWARE += [
'whitenoise.middleware.WhiteNoiseMiddleware', # For serving static files efficiently in production
]
ALLOWED_HOSTS = ['*',"https://0.0.0.0:8000"]
ROOT_URLCONF = 'RootApplication2.urls'
CORS_ORIGIN_ALLOW_ALL = True # Disable allowing all origins
CSRF_COOKIE_SECURE = True # Keep secure CSRF cookies
CSRF_TRUSTED_ORIGINS = [
"https://localhost:8080",
"https://localhost:8000",
"https://127.0.0.1:9000",
"https://0.0.0.0:8000"] # Trust only your production domain
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'RootApplication2',
'USER': 'RootApplication2',
'PASSWORD': 'somePass',
'HOST': 'db',
'PORT': '5432',
}
}
To run it here is the docker-compose.yml
# Goal of this docker-compose is to set up a local test environment.
services:
db:
image: postgres:latest
container_name: postgres_db
restart: always
environment:
POSTGRES_USER: RootApplication
POSTGRES_PASSWORD: somePass
POSTGRES_DB: RootApplication
ports:
- "5432:5432" # Correct port for PostgreSQL
web:
build:
context: .
dockerfile: Dockerfile.test
ports:
- "8000:8000" # Exposing port 8000 to the host
env_file:
- .env.prod
volumes:
- .:/RootApplication # Bind mount local directory to container directory
- static_volume:/RootApplication/staticfiles # Named volume for static files
depends_on:
- db
volumes:
static_volume: # Global volume declaration for static files
Which is using the Dockerfile.test:
COPY requirements.txt /RootApplication/
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
# Copy the project files
COPY . /RootApplication/
RUN echo "Listing contents of /RootApplication:" && ls -R /RootApplication
# Copy the entrypoint script
COPY entrypoint.sh /RootApplication/entrypoint.sh
# Ensure the entrypoint script has Unix-style line endings
RUN sed -i 's/\r$//g' /RootApplication/entrypoint.sh
# Make the entrypoint script executable
RUN chmod +x /RootApplication/entrypoint.sh
# Expose port 8000
EXPOSE 8000
# Use the entrypoint script to run the application
ENTRYPOINT ["/RootApplication/entrypoint.sh"]
The entrypoint script look as follow:
#!/bin/sh
# Debugging: List directory contents
# echo "Listing /RootApplication directory contents:"
# ls -R /RootApplication
python manage.py collectstatic --noinput
#Make migrations
python /RootApplication/manage.py makemigrations
#MIGRATE
python /RootApplication/manage.py migrate
# Create a superuser if specified
if [ "$DJANGO_SUPERUSER_USERNAME" ]; then
echo "Creating superuser $DJANGO_SUPERUSER_USERNAME"
python /RootApplication/manage.py createsuperuser --noinput \
--username $DJANGO_SUPERUSER_USERNAME \
--email $DJANGO_SUPERUSER_EMAIL
fi
# Check the environment variable to decide which server to start
if [ "$DJANGO_ENVIRONMENT" = "development" ]; then
echo "Starting development server"
python /RootApplication/manage.py runserver 0.0.0.0:8000
else
echo "Starting production server with Gunicorn"
exec gunicorn --bind 0.0.0.0:8000 RootApplication.wsgi:application
fi
In Django I have the following url.py
app_name = 'landing_page'
urlpatterns = [
path('', views.home_page, name='home_page'),
path('help/', views.help_page.as_view(), name='help'),
path('privacy/', views.privacy_page.as_view(), name='privacy'),
path('<int:calculationproject_id>', views.Showproject, name='Showproject'),
path('json/',views.profile, name ='profile'),
path('fan/', views.add_items, name='add_items'),
]
Here is the code-snippet of the views.py:
class help_page(TemplateView):
template_name = 'landing_page/help.html'
The html are really basic though.
I appreciate any help