aws ec2 not serving static files in a django react application - python

I am trying to deploy a django react ecommerce app using aws ec2. when i run python manage.py runserver 0.0.0.0:8000 it is loading the page but not serving static files. The errors are
[24/Jun/2021 19:29:26] "GET / HTTP/1.1" 200 2297
[24/Jun/2021 19:29:26] "GET /static/css/2.97503911.chunk.css HTTP/1.1" 404 179
[24/Jun/2021 19:29:26] "GET /static/css/main.4586955f.chunk.css HTTP/1.1" 404 179
[24/Jun/2021 19:29:26] "GET /static/js/2.7e7fd32c.chunk.js HTTP/1.1" 404 179
[24/Jun/2021 19:29:26] "GET /static/js/main.002fbd2b.chunk.js HTTP/1.1" 404 179
Here is my settings.py file
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.1.2.
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
from datetime import timedelta
# 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 = '+^5qu3r54+4ja6q(_$rc!w4*z9t$erk61j=m8wbry53y*c-&h*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_ORIGINS = ['http://localhost:3000']
CORS_ALLOW_CREDENTIALS = True
ALLOWED_HOSTS = ['myamazonclone.ml']
SITE_ID = 1
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'dj_rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'dj_rest_auth.registration',
'rest_framework_simplejwt.token_blacklist',
'users',
'payment',
'products',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
# 'rest_framework.authentication.BasicAuthentication',
)
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': False,
'ALGORITHM': 'HS256',
# 'SIGNING_KEY': settings.SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'AUTH_HEADER_TYPES': ('Bearer', 'JWT'),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=60),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
REST_USE_JWT = True
JWT_AUTH_COOKIE = 'my-app-auth'
JWT_AUTH_REFRESH_COOKIE = 'users-refresh-token'
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',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
ROOT_URLCONF = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR/'frontend'],
'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 = 'backend.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/'
STATIC_ROOT = BASE_DIR/'static'
STATICFILES_DIRS = [BASE_DIR/'frontend/static']
AUTH_USER_MODEL = 'users.User'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
# E-mail address is automatically confirmed by a GET request
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
# Allow logins with an unverified e-mail address
ACCOUNT_EMAIL_VERIFICATION = 'none'
# REST_AUTH_REGISTER_SERIALIZERS = {
# 'REGISTER_SERIALIZER': 'users.serializers.CustomRegistrationSerializer'
# }
AUTHENTICATION_BACKENDS = [
'allauth.account.auth_backends.AuthenticationBackend',
'django.contrib.auth.backends.ModelBackend',
]
I have mentioned the STATIC_ROOT above and have also done python manage.py collectstatic. After doing so it makes a static folder in the root where manage.py is located and it also contains all the files the django is unable to find and gives 404. I also tried using gunicorn but still it is not able to serve static files. I donot understand what mistake i am making . Any help will be really appriciated.
Here is my file structure
Amazon Prod
├─ backend
│ ├─ asgi.py
│ ├─ settings.py
│ ├─ urls.py
│ ├─ wsgi.py
│ ├─ __init__.py
│ └─ __pycache__
│ ├─ settings.cpython-39.pyc
│ ├─ urls.cpython-39.pyc
│ ├─ wsgi.cpython-39.pyc
│ └─ __init__.cpython-39.pyc
├─ db.sqlite3
├─ frontend
│ ├─ asset-manifest.json
│ ├─ favicon.ico
│ ├─ index.html
│ ├─ logo192.png
│ ├─ logo512.png
│ ├─ manifest.json
│ ├─ robots.txt
│ └─ static
│ ├─ css
│ │ ├─ 2.97503911.chunk.css
│ │ ├─ 2.97503911.chunk.css.map
│ │ ├─ main.4586955f.chunk.css
│ │ └─ main.4586955f.chunk.css.map
│ └─ js
│ ├─ 2.7e7fd32c.chunk.js
│ ├─ 2.7e7fd32c.chunk.js.LICENSE.txt
│ ├─ 2.7e7fd32c.chunk.js.map
│ ├─ main.002fbd2b.chunk.js
│ ├─ main.002fbd2b.chunk.js.map
│ ├─ runtime-main.e2a9cdff.js
│ └─ runtime-main.e2a9cdff.js.map
├─ manage.py
├─ payment
├─ products
├─ requirements.txt
├─ static
└─ users
backend is the name of project. frontend is the production build react app.
here is my project urls.py file
from django import urls
from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
from users.views import BlacklistTokenUpdateView
# Allows to render a template without a view
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('rest_framework.urls')),
path('dj-rest-auth/', include('dj_rest_auth.urls')),
path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('blacklist/', BlacklistTokenUpdateView.as_view(), name='blacklist'),
path('payment/', include('payment.urls')),
path('storeApi/', include('products.urls')),
path('', TemplateView.as_view(template_name='index.html'))
]

Check the ownership of the files. If you load your files as ec_user and try to deliver as www-data with 640 permissions you will have 404s.
wild bet.

Related

This engine did not provide a list of tried templates

Wup, I'm trying to deploy a localhost web using Django but I get the following error:
TemplateDoesNotExist at /
templates/index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 4.1.2
Exception Type: TemplateDoesNotExist
I was looking tutorials and docs but I didn't found the answer.
Here is my settings.py
ALLOWED_HOSTS = ['*']
DEBUG = True
ROOT_URLCONF = 'FortyTwop.urls'
SECRET_KEY = 'This is a secret key'
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',
],
},
},
]
also urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index')
]
And views.py
from email import message
from http.client import HTTPResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'index.html')
My path tree:
.
├── FortyTwop
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── templates
│ │ └── index.html
│ ├── tests.py
│ ├── urls.py
│ └── views.py
└── manage.py
What Im doing bad or what I didn't have in the settings?, this project is just for test.
templates/ is the base path you've configured in the settings, so you'll want
def index(request):
return render(request, 'index.html')
Furthermore, TEMPLATE_DIRS hasn't been a thing since Django 1.8 or so, and you're on Django 4.x. See these instructions.

unable to load photos in Django after deploying to heroku

I have made a portfolio + blog website using Django. it works perfectly when running it locally but after I deployed it to Heroku, accessing the portfolio redirected me to a 500 server error. I turned on debug mode and when I did the same, it didn't throw a 500 server error, however, the pictures won't load. this is very confusing and help will be very appreciated...
settings.py
from pathlib import Path
import os
from dotenv import load_dotenv
load_dotenv()
# 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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
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',
'django.contrib.staticfiles',
'projects',
'blog',
]
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'personal_portofolio.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["personal_portofolio/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 = 'personal_portofolio.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
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
import django_heroku
django_heroku.settings(locals())
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'personal_portofolio.settings')
application = get_wsgi_application()
application = WhiteNoise(application)
what my project directory looks like:
C:.
├───blog
│ ├───migrations
│ │ └───__pycache__
│ ├───templates
│ └───__pycache__
├───personal_portofolio
│ ├───templates
│ └───__pycache__
├───projects
│ ├───migrations
│ │ └───__pycache__
│ ├───static
│ │ └───img
│ ├───templates
│ └───__pycache__
└───staticfiles
└───admin
├───css
│ └───vendor
│ └───select2
├───fonts
├───img
│ └───gis
└───js
├───admin
└───vendor
├───jquery
├───select2
│ └───i18n
└───xregexp
Edit: after setting DEBUG_PROPAGATE_EXCEPTIONS to True, I am getting this error in the Heroku logs ValueError: Missing staticfiles manifest entry for 'staticfiles/project1.png'
Your settings.py seems fine, try adding this code to project-name/urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # add static file URL to django urlpatterns
If your trying to host media files note that Heroku does not support media hosting you might need to connect your Django application with something like amazon s3 bucket. You can find an article about it here.

Django application deployment on Heliohost.org problems

I've got an account at heliohost.org (Johnny Server) and I'm desperately trying to deploy a most simple Django application without any success. It's actually a very simple test application to check everything works fine, but it doesn't.
There are several error logs:
https://pastebin.com/xJBB50dF
And these are the most important files' contents:
.htaccess:
RewriteEngine On
RewriteBase /
RewriteRule ^(media/.*)$ - [L]
RewriteRule ^(admin_media/.*)$ - [L]
RewriteRule ^(dispatch\.wsgi/.*)$ - [L]
RewriteRule ^(.*)$ /InformeSO/dispatch.wsgi/$1 [QSA,PT,L]
dispatch.wsgi:
import os, sys
# edit your username below
sys.path.append("/home/alber80/public_html")
from django.core.wsgi import get_wsgi_application
os.environ['DJANGO_SETTINGS_MODULE'] = 'InformeSO.settings'
application = get_wsgi_application()
settings.py:
"""
Django settings for InformeSO project.
Generated by 'django-admin startproject' using Django 3.0.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'nf7w+ajbhz=s_#2y&72&*$v)x#1q2pccrv6t!!*#5l7tx7#$#t'
# 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 = 'InformeSO.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['InformeSO/plantillas'],
'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 = 'InformeSO.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/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/3.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/3.0/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.0/howto/static-files/
STATIC_URL = '/static/'
urls.py:
"""InformeSO URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from InformeSO.views import get_informe
urlpatterns = [
#path('admin/', admin.site.urls),
#path('informe_sistema/', get_informe)
]
views.py:
from django.http import HttpResponse
import datetime
from os import system, uname
from django.template import Template, Context
from django.template.loader import get_template
class Informe(object):
def __init__(self):
self.so = uname().sysname
self.version = uname().version
self.distro = uname().release
self.arquit = uname().machine
def get_informe(request):
informe = Informe()
doc_externo = get_template('informeso.html')
dicc = {"so": informe.so, "version": informe.version,
"distro": informe.distro, "arquitectura": informe.arquit}
documento = doc_externo.render(dicc)
return HttpResponse(documento)
And finally, this is the project's directory tree:
InformeSO
├── db.sqlite3
├── InformeSO
│   ├── asgi.py
│   ├── __init__.py
│   ├── plantillas
│   │   └── informeso.html
│   ├── __pycache__
│   │   ├── __init__.cpython-38.pyc
│   │   ├── settings.cpython-38.pyc
│   │   ├── urls.cpython-38.pyc
│   │   ├── views.cpython-38.pyc
│   │   └── wsgi.cpython-38.pyc
│   ├── settings.py
│   └── views.py
└── manage.py
Although I just realised I'm trying to deploy a Python / Django application which references some modules that might not be available on Heliohost.org, because this site doesn't allow shell access, please let me know if you come up with the issue.
Thank you very much in advance.
Try changing ALLOWED_HOSTS = [] to
ALLOWED_HOSTS = ['*']
Thank you for your answer. I already tried that and it gives another error saying that it cannot find the template referred in the code. I have modified the paths in the code and also the directory structure.
I already solved it by specifying the absolute path of the html document, instead of relative path. Thank you very much for your help. :-)

Why is Django (3.0.6) looking in the wrong directory for admin static files?

I have restructured my django project, and for some reason the django admin loads with no css applied and looking at the log it shows:
Django version 3.0.6, using settings 'config.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[16/May/2020 16:48:33] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1910
Not Found: /admin/login/static/admin/css/login.css
Not Found: /admin/login/static/admin/css/responsive.css
Not Found: /admin/login/static/admin/css/base.css
[16/May/2020 16:48:33] "GET /admin/login/static/admin/css/login.css HTTP/1.1" 404 4875
[16/May/2020 16:48:33] "GET /admin/login/static/admin/css/responsive.css HTTP/1.1" 404 4890
[16/May/2020 16:48:33] "GET /admin/login/static/admin/css/base.css HTTP/1.1" 404 4872
[16/May/2020 16:48:34] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1910
Not Found: /admin/login/static/admin/css/login.css
Not Found: /admin/login/static/admin/css/base.css
Not Found: /admin/login/static/admin/css/responsive.css
[16/May/2020 16:48:34] "GET /admin/login/static/admin/css/base.css HTTP/1.1" 404 4872
[16/May/2020 16:48:34] "GET /admin/login/static/admin/css/login.css HTTP/1.1" 404 4875
[16/May/2020 16:48:34] "GET /admin/login/static/admin/css/responsive.css HTTP/1.1" 404 4890
"/admin/login/static/admin/css/" is not a directory and I am confused. Project structure and settings files below.
<repository root>
│ │db.sqlite3
│ │manage.py
│
│
├───config
│ │ asgi.py
│ │ settings.py
│ │ urls.py
│ │ wsgi.py
│ │ __init__.py
│
│
│
├───docs
└───project
├───media
├───products
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ 0001_initial.py
│ │ __init__.py
│ │
│
│
├───static
│ └───admin
│ ├───css
│ │ autocomplete.css
│ │ base.css
│ │ changelists.css
│ │ dashboard.css
│ │ fonts.css
│ │ forms.css
│ │ login.css
│ │ responsive.css
│ │ responsive_rtl.css
│ │ rtl.css
│ │ widgets.css
│
│
├───templates
│ base.html
│ index.html
settings.py
import os
import sys
from pathlib import Path
# This is the <repository root>
BASE_DIR = Path(__file__).resolve().parent.parent
# This is the <project repository>
PROJECT_DIR = BASE_DIR / 'swiftr'
# Append to the system path
sys.path.append(os.path.join(BASE_DIR, PROJECT_DIR))
MEDIA_ROOT = PROJECT_DIR / 'media'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_ROOT = PROJECT_DIR / 'static'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
STATIC_URL = 'static/'
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'f#&1x0!uyqn^hm(g67#_^o999tchl3aczwvtarj3p&u*9wj3sn'
# 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',
'taggit',
'products',
]
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 = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [PROJECT_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 = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/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/3.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/3.0/topics/i18n/
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
I have tried collectstatic and that is why it has created a static directory within the project directory. If you need to see anything else, please let me know.
The problem seemed to be the STATIC_URL. It required a backsplash before and after '/static/' once this was amended the CSS loaded.

404 error for static files in console with Django and Heroku

I am able to run collectstatic fine when I push to Heroku. The problem now is I that I'm not sure how to reference them when they're stored on the server.
For example for my stylesheets I get a 404 error:
<link rel="stylesheet" type="text/css" href="/static/bower_components/bootstrap-material-design/dist/css/material.css" />
This is the URL in the console that is causing the 404:GET https://tixblast-membership.herokuapp.com/static/bower_components/bootstrap-material-design/dist/css/material.css net::ERR_ABORTED 404 (Not Found)
What part of my settings to I alter to make sure I look in the right place? I ran heroku run python manage.py findstatic --verbosity 2 css/styles.css
to show where it was looking for static files and it returned:
/app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/static
/app/.heroku/python/lib/python3.7/site-packages/rest_framework/static
So do I need to include one of the above directories in my settings?
I assumed that after I got collectstatic working I'd be fine, here is my settings.py:
"""
Django settings for thinkster_django_angular_boilerplate project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import django_heroku
PROJECT_DIR = os.path.dirname(__file__)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/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 = os.environ.get('DEBUG', True)
TEMPLATE_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',
'rest_framework',
'authentication'
)
MIDDLEWARE_CLASSES = (
'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 = 'thinkster_django_angular_boilerplate.urls'
WSGI_APPLICATION = 'thinkster_django_angular_boilerplate.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
import dj_database_url
DATABASES = {
'default': dj_database_url.config(
default='sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3')
)
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/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.7/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR,'static'),
],
'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',
],
},
},
]
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'compressor.finders.CompressorFinder',
)
COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
)
}
# 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 = ['*']
AUTH_USER_MODEL = 'authentication.Account'
django_heroku.settings(locals())
edit:
My stylesheet:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'bower_components/bootstrap/dist/css/bootstrap.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'bower_components/bootstrap-material-design/dist/css/material.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'bower_components/bootstrap-material-design/dist/css/ripples.min.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'bower_components/ngDialog/css/ngDialog.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'bower_components/ngDialog/css/ngDialog-theme-default.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'lib/snackbarjs/snackbar.min.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'stylesheets/styles.css' %}" />
edit2:
file structure where my app is located, its in the same folder as my settings.py. Which is the only way heroku would notice it:
└───static
├───bower_components
│ ├───angular
│ ├───angular-cookies
│ ├───angular-route
│ ├───bootstrap
│ │ ├───dist
│ │ │ ├───css
│ │ │ ├───fonts
│ │ │ └───js
│ │ ├───fonts
│ │ ├───grunt
│ │ ├───js
│ │ ├───less
│ │ │ └───mixins
│ │ └───nuget
│ ├───bootstrap-material-design
│ │ ├───dist
│ │ │ ├───css
│ │ │ ├───fonts
│ │ │ └───js
│ │ ├───fonts
│ │ ├───less
│ │ ├───sass
│ │ └───scripts
│ ├───jquery
│ │ ├───dist
│ │ └───src
│ │ ├───ajax
│ │ │ └───var
│ │ ├───attributes
│ │ ├───core
│ │ │ └───var
│ │ ├───css
│ │ │ └───var
│ │ ├───data
│ │ │ └───var
│ │ ├───effects
│ │ ├───event
│ │ ├───exports
│ │ ├───manipulation
│ │ │ └───var
│ │ ├───queue
│ │ ├───sizzle
│ │ │ └───dist
│ │ ├───traversing
│ │ │ └───var
│ │ └───var
│ ├───ngDialog
│ │ ├───css
│ │ └───js
│ └───underscore
├───javascripts
│ └───authentication
│ ├───controllers
│ │ └───New folder
│ └───services
└───lib
└───snackbarjs
edit 3:
This is where django is looking for the templates according to the error screen:
Using engine django:
django.template.loaders.filesystem.Loader: /app/static/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/templates/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/templates/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/rest_framework/templates/index.html (Source does not exist)
Going off what works for me, try deleting STATICFILES_FINDERS setting. I don't think this is necessary for serving static with whitenoise. In any case I don't use it. Also, instead of MIDDLEWARE_CLASSES I just have MIDDLEWARE. Other than those minor changes I would just say try running your app with Debug=False on your local server and see if you run into problems.
Try changing your BASE_DIR setting to:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
You should not hardcode static files URLs in your template when using static-files Django app instead, try the following in order to set up the static-files properly.
Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
In your settings file, define STATIC_URL
example:
STATIC_URL = '/static/'
In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE:
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">
I fixed it, I added the NodeJS buildback to Heroku. That installed the bower_components in the right folder. I'm using Python and Angular so I had the buildpack for the former but not the latter.

Categories