Django DEBUG False not working in the Production Environment - django

I am new to Django and Python world, I am currently working on an Dajngo site, which is hosted on a Ubuntu20.04 VM. Upon hosting the site to the production, I noticed that, although the DEBUG is set to False in the prodiuction settings. I still see the Django DEBUG erros as if the DEBUG is set to True .
When I run python manage.py runserver command on the VM I get the below error.
CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.
Folder structure
.
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-310.pyc
│ ├── urls.cpython-310.pyc
│ ├── views.cpython-310.pyc
│ └── wsgi.cpython-310.pyc
├── settings
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-310.pyc
│ │ ├── base.cpython-310.pyc
│ │ ├── local.cpython-310.pyc
│ │ └── production.cpython-310.pyc
│ ├── base.py
│ ├── local.py
│ └── production.py
base.py (Common settings)
import os
from os.path import dirname, join
import posixpath
from posixpath import join
from pathlib import Path
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '393266f4-9cc7-4cfe-96a8-2f2809e53e32'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#ALLOWED_HOSTS = []
# Application references
INSTALLED_APPS = [
# Add your apps here to enable them
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'AssayBlog',
'AssayCMS',
'ckeditor',
'ckeditor_uploader',
]
# Middleware framework
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 = 'AssaySite.urls'
# Template configuration
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 = 'AssaySite.wsgi.application'
# Database
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
#}
# Password validation
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
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# HTTPS SETTINGS
SESSIONS_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True #False
SECURE_SSL_REGIRECT = True
# HSTS SETTINGS
SECURE_HSTS_SECONDS = 31536000 # 1 YEAR
SECURE_HSTS_PRELOAD = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
CKEDITOR_UPLOAD_PATH = "uploads/"
production.py
from AssaySite.settings.base import *
DEBUG = False
ALLOWED_HOSTS = [
'www.exampl.com',
'example.com',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'abssaysitedb',
'USER': 'admingres',
'PASSWORD': 'password',
'HOST': '192.168.1.201',
'PORT': '8686',
}
}
local.py
from AssaySite.settings.base import *
DEBUG = False
ALLOWED_HOSTS = [
'127.0.0.1',
'localhost'
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'admin',
'HOST': 'localhost',
'PORT': '5432',
}
}
I have carefully reviewed the settings code to see if the DEBUG is True in any part of my code but everything looks good.
Please help

You need to ALLOWED_HOSTS variable in settings.py.
ALLOWED_HOSTS = ['your_domain.com','www.your_domain.com']
or, this will allow all the domain which is not recommended
ALLOWED_HOSTS = ['*']

I am also having the same issue however I am using the .env file to manage the settings.
settings.py # my settings file
DEBUG = env('DEBUG')
.env # my .env file
DEBUG=False
the app works exactly as intended except for for the debug part, by the way the app hosted on ubuntu 20.04

Related

Django custom management command not found

app/
├─ management/
│ ├─ commands/
│ │ ├─ customcommand.py
myfunction.py
site/
├─ settings.py
Content of settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 4.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
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/4.1/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 = 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',
'app'
]
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 = 'site.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 = 'site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# 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 = 'Asia/Kolkata'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
]
}
Content of customcommand.py
from django.core.management.base import BaseCommand, CommandError
import time
import requests
class Command(BaseCommand):
help = 'Closes the specified poll for voting'
def handle(self, *args, **options):
print("execued the commands success!!")
start_time = time.time()
for number in range(1, 50):
url = f'https://pokeapi.co/api/v2/pokemon/{number}'
resp = requests.get(url)
pokemon = resp.json()
print(pokemon['name'])
print("--- %s seconds ---" % (time.time() - start_time))
Contents of myfunction.py
from django.core import management
def funcA():
management.call_command('customcommand')
funcA()
On calling myfunction.py from terminal it throws raise CommandError("Unknown command: %r" % command_name)
os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings'
Inside myfunction.py I have tried setting this, but it still doesn't work. Can someone help me out here, probably I am missing out on some important config
Try adding __init__.py to management/ and commands/ directories.
I have solved the issue by adding the django.setup() call, after configuring the environment variable.
Inside myfunction.py, the following changes should be made
from django.core import management
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'site.settings')
django.setup()
def funcA():
management.call_command('customcommand')
funcA()
django.setup() is essential to include because it registers your applications and commands defined in your settings in a standalone script which the manage.py or django-admin takes care usually

deploying django to heroku :page not found error

I have been making a django app, and am now trying to deploy it to heroku. However when I go on it,says page not found
the resources not found on the server
and i am trying it on different app error remains same
Here is my settings.py (at learst the relevant parts, but please ask if you would like the rest):
"""
Django settings for django_deployment project.
Generated by 'django-admin startproject' using Django 4.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
import django_heroku
import dj_database_url
from decouple import config
# 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.0/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 = True
ALLOWED_HOSTS = ['django-deployment85.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',
'myapp'
]
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 = 'django_deployment.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 = 'django_deployment.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.0/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.0/howto/static-files/
STATIC_URL = 'static/'
#STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
django_heroku.settings(locals())
#and here is my requirement.txt
asgiref==3.4.1
backports.entry-points-selectable==1.1.1
certifi==2021.10.8
distlib==0.3.4
dj-database-url==0.5.0
Django==4.0
django-heroku==0.3.1
filelock==3.4.0
gunicorn==20.1.0
pipenv==2021.11.23
platformdirs==2.4.0
psycopg2==2.9.3
python-decouple==3.6
six==1.16.0
sqlparse==0.4.2
tzdata==2021.5
virtualenv==20.10.0
virtualenv-clone==0.5.7
virtualenvwrapper-win==1.2.6
waitress==2.0.0
whitenoise==6.0.0
Also, when I run the app locally with python manage.py runserver it works fine, it only doesn't work when I use heroku.
Please tell me if you need anymore information.
You may have postgres in Heroku, but your settings.py shows that you are still using SQLite. The DATABASES section should look like:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'database_name_goes_here',
'USER': 'username_goes_here',
'PASSWORD': 'password_goes_here',
'HOST': 'localhost',
'PORT': '',
}
}
The database name, user, and password you can get by going to your database, then click settings, then credentials.
There are several steps to deploying Django on Heroku. Configuring Postgres is just one. There's a nice tutorial at https://dev.to/giftedstan/heroku-how-to-deploy-a-django-app-with-postgres-in-5-minutes-5lk.

django not switching to Postres when deploying to Heroku

I deployed my django app with Heroku and I am having troubles with connecting to Postgres.
If I run python manage.py createsuperuser after running heroku ps:exec --app produceit (so I am inside the Heroku instance's terminal), it says that I successfully created a superuser but nothing is written into Heroku Postgress DB...so I can't login into neither /admin nor my app.
I therefore run
heroku ps:exec --app produceit
python manage.py shell
from mywebsite.settings import DATABASES
and it seems like the settings.py has the variable DATABASE still connected to sqlite (see pic)
Funny enough, if I hardcode an admin into Heroku's Postgres DB, loging and then create an instance of one of my models from the app itself (like I create a blog's post)...it actually writes into Postgres and I see it on the Front End.
So basically it's like the app is working on Postgress BUT the terminal is running on SQLite.
What can I do? My settings are below
"""
Django settings for mywebsite project.
Generated by 'django-admin startproject' using Django 3.2.5.
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/
"""
from pathlib import Path
import os
# 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 = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG=True
DEBUG_PROPAGATE_EXCEPTIONS = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'produceit.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'action.apps.ActionConfig',
'django_extensions',
'bootstrap_modal_forms',
'widget_tweaks',
]
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 = 'mywebsite.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 = 'mywebsite.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',
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.postgresql',
# 'NAME': '',
# 'HOST': '',
# 'PORT': 5432,
# 'USER': '',
# 'PASSWORD': '',
# }
# }
# Parse database configuration from $DATABASE_URL
#import dj_database_url
#db_from_env = dj_database_url.config(conn_max_age=500)
#DATABASES['default'].update(db_from_env)
# 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 files (CSS, JavaScript, Images)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
#DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
import django_on_heroku
django_on_heroku.settings(locals())
#SECURE_SSL_REDIRECT=True
#SESSION_COOKIE_SECURE=True
#CSRF_COOKIE_SECURE=True
#SECURE_HSTS_SECONDS = 31536000
#SECURE_HSTS_INCLUDE_SUBDOMAINS=True
#SECURE_HSTS_PRELOAD=True
#import django_heroku
#django_heroku.settings(locals())
To get the correct environment variables etc., connect to the terminal via the Heroku dashboard and try it again. You can find it in "More" > "Run Console" > Type in "Bash" on your Heroku-app.

'NoneType' object is not iterable in Django project

I am getting "'NoneType' object is not iterable" error while I try to run my django app using " python manage.py runserver ip:port" whereas the same error does not occur if I use " python manage.py runserver 0.0.0.0:8000". I really need to get this work using my ip address.
Link to the error page 1 and
Link to the error page 2
What am I doing wrong?
This is how my settings.py looks like:
"""
Django settings for SimStudent project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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.2/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 = True
#ALLOWED_HOSTS = ['0.0.0.0', '10.153.1.51', '127.0.0.1']
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'channels',
'chat',
'django_tables2',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'SimStudent'
]
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 = 'SimStudent.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'SimStudent.context_processor.tutor_tutee_session_info',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'SimStudent.wsgi.application'
ASGI_APPLICATION = 'SimStudent.routing.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
#'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#}
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'simstudent_oz',
'USER': 'sim_tasmia',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '5433',
}
}
# 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, "static/")
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
And my context_processor.py looks like:
from django.shortcuts import get_object_or_404
from django.utils.safestring import mark_safe
import json
from chat.models import Session, TutorTuteeConversation
from django.core import serializers
from chat.models import Session
def tutor_tutee_session_info(request):
if 'session_id' in request.session:
session_id = request.session['session_id']
room_name = request.session['room_name']
print("inside context", session_id)
session = get_object_or_404(Session, pk=int(session_id))
chat_history = TutorTuteeConversation.objects.filter(session_id=int(session_id)).order_by('comment_time')
dict_chat_history = serializers.serialize("json", chat_history)
print("dict chat history inside context", dict_chat_history)
return {
"session_info": session,
"chat_history": mark_safe(json.dumps(dict_chat_history)),
"room_name": room_name,
}
Project directory structure is here
It happened to me and solved by making else returning an empty dict for example:
def test(request):
if condition:
return {"val":val}
else:
return {}

STATIC_ROOT in Django not working correctly

Trying to get static root set properly,
Went through the tango with Django tutorial and stuck on this part.
Basically this is my setting files, and the static folder is linked below in the tree.
C:.
├───media
│ └───locations
│ └───2018
│ └───11
│ └───11
│ └───20
│ └───18
├───Space
│ └───__pycache__
├───Spaces
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
├───static
│ ├───admin
│ │ ├───css
│ │ │ └───vendor
│ │ │ └───select2
│ │ ├───fonts
│ │ ├───img
│ │ │ └───gis
│ │ └───js
│ │ ├───admin
│ │ └───vendor
│ │ ├───jquery
│ │ ├───select2
│ │ │ └───i18n
│ │ └───xregexp
│ ├───css
│ └───images
│ └───parralax
│ └───home
├───templates
│ ├───registration
│ └───Spaces
└───users
├───migrations
│ └───__pycache__
└───__pycache__
and below you can see the settings i'm using for this .
"""
Django settings for Space project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')
MEDIA_DIR = os.path.join(BASE_DIR,'media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '5a#tkcbah13t_vb!6pp6#z1c3j-3abb!&$6r-mw+%0mtzg$qo#'
# 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',
'django.contrib.sites',
'users',
'Spaces',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
]
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 = 'Space.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'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'
],
},
},
]
STATICFILES_DIRS = [STATIC_DIR, ]
STATIC_URL = '/static/'
MEDIA_ROOT = MEDIA_DIR #where to look for files
MEDIA_URL = '/media/' #where to serve files from on url
WSGI_APPLICATION = 'Space.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/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/2.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',
},
]
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
AUTH_USER_MODEL = 'users.CustomUser'
SITE_ID = 1
LOGIN_REDIRECT_URL = 'home'
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOGIN_REDIRECT_URL = 'index'
LOGOUT_REDIRECT_URL = 'index'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
essentially just want the root for static to be where i've put "static" in the directory.
Essentially I'm uploading to Heroku ATM, and I'm getting an error that it can't find the static root.
When changing my STATIC_ROOT to,
STATICFILES_DIRS = [STATIC_DIR, ]
STATIC_URL = '/static/'
MEDIA_ROOT = MEDIA_DIR #where to look for files
MEDIA_URL = '/media/' #where to serve files from on url
WSGI_APPLICATION = 'Space.wsgi.application'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
I get this issue :(