unable to load photos in Django after deploying to heroku - python

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.

Related

aws ec2 not serving static files in a django react application

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.

Django admin site is not showing default permissions of models

My Django admin site does not show any default permissions of any models. Actually, I checked the database and I can't find any model permission in the auth_permissions table.
I've already run python manage.py makemigrations and python manage.py migrate. I also tried deleting the database and migration files and run two above command again but doesn't work. I've already registered my models in admin.py.
Any other solutions I can try ?
admin.py
from django.contrib import admin
from .Models import *
# Register your models here.
admin.site.register(LeaveRequest)
admin.site.register(Worker)
admin.site.register(TimeSheet)
settings.py
"""
Django settings for WorkTime project.
Generated by 'django-admin startproject' using Django 3.1.3.
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
import os
import rest_framework
import dj_database_url
# 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 = '0yz04(%a^xuilqa8*#e^e)bj+n%&+jou=tg$%lb&#ox!lk1!x5'
SECRET_KEY = os.environ.get(
'SECRET_KEY', '0yz04(%a^xuilqa8*#e^e)bj+n%&+jou=tg$%lb&#ox!lk1!x5')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', '') != 'False'
ALLOWED_HOSTS = ['worktime-management.herokuapp.com', '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',
'rest_framework',
'api',
'rest_framework.authtoken',
'crispy_forms',
'web',
]
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 = 'WorkTime.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 = 'WorkTime.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_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = [
STATIC_DIR,
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Heroku: Update database configuration from $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Media root
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Email config
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD = os.environ.get('MAIL_PASSWORD')
EMAIL_HOST_USER = os.environ.get('MAIL_USERNAME')
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
# CSRF enable
CSRF_COOKIE_SECURE = True
# Rest Auth
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}
# Boostrap4
CRISPY_TEMPLATE_PACK = 'bootstrap4'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.AllowAllUsersModelBackend', )
In your admin.py you are importing all of your models as from .Model import *. Python is a case-sensitive programming language if you have not manipulated your models.py file as Models.py.
I suppose from .models import * will do the trick
The above solution solves the problem. However, my Models is actually a folder, I've been trying to divide the models into different files which are stored in that folder. So for those who have the same idea, just simply change the folder's name into models and you're good to go :v

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. :-)

Cant start new app in django when I split settings.py file

I splited my settings.py like this:
# __init__.py
from .base import * # noqa
try:
from .local_settings import * # noqa
except ImportError:
message = 'ERROR: Unable to import local_settings. Make sure it exists.'
raise ImportError(message)
# base.py
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 3.0.4.
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.dirname(os.path.abspath(__file__))))
# Add the apps folder to python path
os.sys.path.append(os.path.join(BASE_DIR, 'apps'))
# 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 = 'app.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 = 'app.wsgi.application'
# 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',
},
]
and:
# local_settings.py
import os
from .base import BASE_DIR
# 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 = '670b9a538dfe8545f4eff723345da43211084a05f520a2d638'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'run/db.sqlite3'),
}
}
# 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/'
Every command works good except python manage.py startapp myapp [or any other app name] ./apps/myapp. Every time I run it command I get this error:
CommandError: 'myapp' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name.
I found it related with my code in __init__.py file. I mean if I comment all the codes, that error will be disappear.
Why does it happend? How can I solve it?
With Directory
Without Directory
As #juggernaut has stated. The error is happening when you use the character *, which imports everything and hence overwrites some internal.
When you run the command python manage.py startapp myapp xxxx The myapp section conflicts with an existing module and hence causes that error.
Try importing it manually instead of using from .base import * # noqa. This way you only import the modules that you will need and would not lead to any errors.

Django: ImproperlyConfigured The SECRET_KEY setting must not be empty when executing gunicorn

I'm trying to deploy a django application on AWS. I've read all the existing posts regarding the same issue and include the
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tango_with_django.settings")
in manage.py and wsgi.py but still it does not work.
My project structure is the following one:
--chimpy
-botApp
-settings
-base.py
-production.py
-wsgi.py
-manage.py
These are my files:
-base.py:
"""
Django settings for botApp project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.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/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'whatever'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
LOCALE_PATHS = [
os.path.join(BASE_DIR, '../../locale'),
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'profiles',
'portfolios',
'django_extensions',
'rest_framework',
'corsheaders',
]
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 = 'botApp.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',
],
'libraries':{
'proper_paginate': 'portfolios.proper_paginate',
'url_replace': 'portfolios.url_replace',
}
},
},
]
WSGI_APPLICATION = 'botApp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django_db',
'USER': 'db_user',
'PASSWORD': 'whatever',
'HOST': 'localhost',
'PORT': '',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.0/howto/static-files/
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "../../static"), '/Users/ibotics/suribit/static', ]
STATIC_ROOT = "/Users/ibotics/suribit/static_cdn"
TEMPLATE_DIRS = ('/templates/',)
LOGIN_URL = '/login'
# media config missing
# static cdn missing?
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'localhost:8080','localhost:8000',
)
CORS_ORIGIN_REGEX_WHITELIST = (
'localhost:8080','localhost:8000',
)
-production.py:
from .base import *
DEBUG = False
ALLOWED_HOSTS = ['*']
-wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "botApp.settings.production")
application = get_wsgi_application()
-manage.py:
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "botApp.settings.production")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
As you can see all files point to the settings/production.py file, which imports everything from base.py and I have the secret key in there, but still receive the same error Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty when I try to do:
gunicorn botApp.wsgi:application --bind 0.0.0.0:8001
Many thanks.

Categories