Django admin broken template when using uwsgi

Question:

When I start my application using python3 manage.py run server 0.0.0.0:8000 I can access Django admin just fine.
However, when I run it using uwsgi the Django admin template is broken. The application works fine, but the website is displayed as simple text, no templates at all. For instance, here’s the login page:
enter image description here

How can I fix this?
This my uwsgi.ini:

[uwsgi]
chdir               = ./src
http                = :8000
enable-threads      = true
#harakiri           = 300
master              = true
module              = config.wsgi:application
#processes           = $(UWSGI_PROCESSES)
#threads             = $(UWSGI_THREADS)
#max-worker-lifetime = $(UWSGI_MAX_WORKER_LIFE)
workers             = 32
thunder-lock        = true
vacuum              = true
workdir             = ./src
add-header          = Connection: Keep-Alive
http-keepalive      = 65000
max-requests        = 50000
max-requests-delta  = 10000
max-worker-lifetime = 360000000000         ; Restart workers after this many seconds
reload-on-rss = 2048                 ; Restart workers after this much resident memory
worker-reload-mercy = 60             ; How long to wait before forcefully killing workers
# Increment the timeout to reach the target app.
# http-timeout      = 60
lazy-apps           = true
single-interpreter = true
ignore-sigpipe      = true
ignore-write-errors = true
http-auto-chunked   = true
disable-write-exception = true

This is the settings.py for my app:

"""
Django settings for config project.

Generated by 'django-admin startproject' using Django 3.2.7.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

import os
from pathlib import Path

import socket

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = (Path(__file__).resolve().parent.parent / '..').resolve()


# 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 = 'django-insecure-yn8)g036-ul$ge)b=$)*mn0k$%_xl0f(_*)24j)r=w5o%v)(2z'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = [
    '127.0.0.1',
    'localhost',
    'host.docker.internal',
    '3.236.90.54',
    socket.gethostbyname(socket.gethostname())
]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
    'http://35.153.126.53:8000',
)

INTERNAL_IPS = [
    '127.0.0.1',
]

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 3rd party
    'corsheaders',
    'debug_toolbar',
    'django_extensions',
    'django_filters',
    'drf_yasg',
    'polymorphic',
    'rest_framework',
    # Local
    'vehicles',
    'api'
]

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

DEBUG_TOOLBAR_PANELS = [
    'debug_toolbar.panels.history.HistoryPanel',
    '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',
    'debug_toolbar.panels.profiling.ProfilingPanel',
]

ROOT_URLCONF = 'config.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 = 'config.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'data/django/db.sqlite3',
        'CONN_MAX_AGE': None
    }
}

# Cache
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/home/ubuntu/pycharm/projects/ai-datasets/django_cache',
        'TIMEOUT': None,  # never expires
        'OPTIONS': {
            'MAX_ENTRIES': 1e6
        }
    }
}


# 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/'

# Base url to serve media files
MEDIA_URL = '/media/'

# Path where media is stored
MEDIA_ROOT = os.path.join(BASE_DIR, 'data/django/media/')

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# REST_FRAMEWORK
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}

# LOGGING = {
#     'version': 1,
#     'disable_existing_loggers': False,
#     'handlers': {
#         'console': {
#             'class': 'logging.StreamHandler',
#         },
#     },
#     'root': {
#         'handlers': ['console'],
#         'level': 'WARNING',
#     },
#     'loggers': {
#         'django': {
#             'handlers': ['console'],
#             'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
#             'propagate': False,
#         },
#     },
# }
#
# LOGGING['loggers']['django.db.backends'] = {
#     'handlers': ['console'],
#     'level': 'DEBUG',
# }

Also, here’s the console errors that I see in Safari:

[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (base.css, line 0)
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (nav_sidebar.css, line 0)
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (nav_sidebar.js, line 0)
[Error] Refused to execute http://myip...:8000/static/admin/js/nav_sidebar.js as script because "X-Content-Type-Options: nosniff" was given and its Content-Type is not a script MIME type.
[Error] Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'i.generateKey')
    promiseEmptyOnRejected (content-script.js:75:780)
    promiseReactionJob
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (login.css, line 0)
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (responsive.css, line 0)

EDIT: here’s the network calls for the css/js files as requested

enter image description here

Asked By: user1315621

||

Answers:

I set up NGINX and it helped to solve the issue. However, I still don’t know what caused the issue in the first place, and how to solve it without NGINX.

Answered By: user1315621
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.