Below is the problem i am facing while running the server.
I'm not able to start manage.py runserver . I'm Using sqlite3 database. I am trying to run quite basic application. system configurations: windows 10, python 2.7.
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.
C:\Users\rutwi_000>cd C:\Python27\Scripts\mysite
C:\Python27\Scripts\mysite>C:/Python27/python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 195, in fetch_command
klass = load_command_class(app_name, subcommand)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 39, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 16, in <module>
from django.db.migrations.executor import MigrationExecutor
File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 7, in <module>
from .loader import MigrationLoader
File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 10, in <module>
from django.db.migrations.recorder import MigrationRecorder
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 12, in <module>
class MigrationRecorder(object):
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 26, in MigrationRecorder
class Migration(models.Model):
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 27, in Migration
app = models.CharField(max_length=255)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1072, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 166, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 99, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Python27\Scripts\mysite\mysite\settings.py", line 15, in <module>
django.setup()
File "C:\Python27\lib\site-packages\django\__init__.py", line 17, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 120, in __init__
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Please help me with this question. Thanks!!!!!!
Below is the settings.py file.
Note: I do have a security key (not shown in the code below)
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import django
django.setup()
# 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/1.9/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 = [
'personal',
'blog',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'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 = 'mysite.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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/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/1.9/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/1.9/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.9/howto/static-files/
STATIC_URL = '/static/'
Your error traceback clearly states that your SECRET_KEY is empty
raise ImproperlyConfigured("The SECRET_KEY setting must not be
empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Generate a new one, you can use this
"""
Pseudo-random django secret key generator.
- Does print SECRET key to terminal which can be seen as unsafe.
"""
from __future__ import print_function
import string
import random
# Get ascii Characters numbers and punctuation (minus quote characters as they could terminate string).
chars = ''.join([string.ascii_letters, string.digits, string.punctuation]).replace('\'', '').replace('"', '').replace('\\', '')
SECRET_KEY = ''.join([random.SystemRandom().choice(chars) for i in range(50)])
print(SECRET_KEY)
save this in secret_key.py file, and do python secret_key.py, it will generate you a new SECRET KEY, then just copy new SECRET_KEY inside you're settings.py file.
Related
I'm building a Django app but I've got an issue. I've imported the environ package in order to store all my variables in a .env file, but actually it seems my app doesn't read it and I can't get why.
Here is my .env file:
DEBUG=True
SECRET_KEY='<SECRET>'
DB_NAME=<SECRET>
DB_USER=<SECRET>
DB_PASSWORD=<SECRET>
DB_HOST=localhost
DB_PORT=
EMAIL_HOST=
EMAIL_HOST_USER=
EMAIL_HOST_PASSWORD=
EMAIL_PORT=
DEFAULT_FROM_EMAIL=<SECRET>
Here is my settings.py file:
from pathlib import Path
import environ
env = environ.Env(
DEBUG=(bool, False)
)
READ_DOT_ENV_FILE = env.bool('READ_DOT_ENV_FILE', default=False)
if READ_DOT_ENV_FILE:
environ.Env.read_env()
DEBUG = env('DEBUG')
SECRET_KEY = env('SECRET_KEY')
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third party apps
'crispy_forms',
'crispy_tailwind',
'tailwind',
'theme',
# Local apps
'leads',
'agents',
]
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 = 'djcrm.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 = 'djcrm.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': env("DB_NAME"),
'USER': env("DB_USER"),
'PASSWORD': env("DB_PASSWORD"),
'HOST': env("DB_HOST"),
'PORT': env("DB_PORT"),
}
}
# 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/'
STATICFILES_DIRS = [
BASE_DIR / "static"
]
MEDIA_URL = '/media/'
MEDIA_ROOT = "media_root"
STATIC_ROOT = "static_root"
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
AUTH_USER_MODEL = 'leads.User'
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
LOGIN_REDIRECT_URL = "/leads"
LOGIN_URL = "/login"
LOGOUT_REDIRECT_URL = "/"
CRISPY_ALLOWED_TEMPLATE_PACKS = "tailwind"
CRISPY_TEMPLATE_PACK = 'tailwind'
if not DEBUG:
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_HSTS_SECONDS = 31536000 # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
X_FRAME_OPTIONS = "DENY"
ALLOWED_HOSTS = ["*"]
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = env("EMAIL_HOST")
EMAIL_HOST_USER = env("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD")
EMAIL_USE_TLS = True
EMAIL_PORT = env("EMAIL_PORT")
DEFAULT_FROM_EMAIL = env("DEFAULT_FROM_EMAIL")
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'WARNING',
},
}
TAILWIND_APP_NAME = 'theme'
When I run the python manage.py runserver command (or any other command btw), I get this error:
Traceback (most recent call last):
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/environ/environ.py", line 273, in get_value
value = self.ENVIRON[var]
File "/opt/homebrew/Cellar/python#3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__
raise KeyError(key) from None
KeyError: 'SECRET_KEY'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/davidemancuso/Dev/django-crm/manage.py", line 22, in <module>
main()
File "/Users/davidemancuso/Dev/django-crm/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 61, in execute
super().execute(*args, **options)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 68, in handle
if not settings.DEBUG and not settings.ALLOWED_HOSTS:
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/conf/__init__.py", line 83, in __getattr__
self._setup(name)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/conf/__init__.py", line 70, in _setup
self._wrapped = Settings(settings_module)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/conf/__init__.py", line 177, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/opt/homebrew/Cellar/python#3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 790, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/Users/davidemancuso/Dev/django-crm/djcrm/settings.py", line 13, in <module>
SECRET_KEY = env('SECRET_KEY')
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/environ/environ.py", line 123, in __call__
return self.get_value(var, cast=cast, default=default, parse_default=parse_default)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/environ/environ.py", line 277, in get_value
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
Now, if I put the secret key hard-coded into the settings.py, the error changes in:
django.core.exceptions.ImproperlyConfigured: Set the DB_NAME environment variable
As far as I can see, it seems the settings.py is not reading at all the variables in the .env, but I don't know how to solve this. What can I do?
EDIT: PROBLEM SOLVED
It was easier than I thought. I forgot to type in the terminal export READ_DOT_ENV_FILE=True in order to enable the file reading in development.
Thanks to all who try to help me!
Have a nice day
PROBLEM SOLVED
It was easier than I thought. I forgot to type in the terminal export READ_DOT_ENV_FILE=True in order to enable the file reading in development.
Thanks to all who try to help me!
Have a nice day
Make sure that your .env file is in the same directory as your settings.py.
This may be a hard way
Try following code for every variable in the console
export SECRET_KEY='<SECRET>'
When I run collectstatic on my Django site, I always get an error.
This is my settings.py:
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 3.1.1.
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/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIRS = os.path.join(BASE_DIR, 'templates')
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )
# 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 = 'not showing it here'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'news',
'writers',
]
INSTALLED_APPS += ('django_summernote', )
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',
'news.middleware.TimezoneMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_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',
'news.context_processors.common_variables'
],
},
},
]
WSGI_APPLICATION = 'mysite.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/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
X_FRAME_OPTIONS = 'SAMEORIGIN'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
When I run collectstatic I get:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\management\base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\management\base.py", line 371, in execute
output = self.handle(*args, **options)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\management\commands\collectstatic.py", line 194, in han
dle
collected = self.collect()
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\management\commands\collectstatic.py", line 132, in col
lect
for original_path, processed_path, processed in processor:
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\wh
itenoise\storage.py", line 148, in post_process_with_compression
for name, hashed_name, processed in files:
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\wh
itenoise\storage.py", line 88, in post_process
for name, hashed_name, processed in files:
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 399, in post_process
yield from super().post_process(*args, **kwargs)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 231, in post_process
for name, hashed_name, processed, _ in self._post_process(paths, adjustable_
paths, hashed_files):
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 288, in _post_process
content = pattern.sub(converter, content)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 187, in converter
hashed_url = self._url(
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 126, in _url
hashed_name = hashed_name_func(*args)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 338, in _stored_name
cache_name = self.clean_name(self.hashed_name(name))
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\wh
itenoise\storage.py", line 166, in hashed_name
name = super(CompressedManifestStaticFilesStorage, self).hashed_name(
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 87, in hashed_name
if not self.exists(filename):
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\files\storage.py", line 311, in exists
return os.path.exists(self.path(name))
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 41, in path
return super().path(name)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\files\storage.py", line 324, in path
return safe_join(self.location, name)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\utils\_os.py", line 29, in safe_join
raise SuspiciousFileOperation(
django.core.exceptions.SuspiciousFileOperation: The joined path (E:\Folder\WebProjects\website\mysite\img\arrow-left.png) is l
ocated outside of the base path component (E:\Folder\WebProjects\website\mysite\staticfiles)
I've searched but I can't find E:\Folder\WebProjects\website\mysite\img\arrow-left.png
This only happens when I use Whitenoise. If I use the normal Django static service, It works but the CSS doesn't show. I'm using Heroku
EDIT: Here's my wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application()
Comment whitenoise part in wsgi.py then run collectstatic and uncomment whitenoise part while deployment.
Also no need of STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage
sample for wsgi.py
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
I have Django application inside IntelliJ IDE.
I can run all Django tests by calling the Django Tests runner.
But:
This is a time consuming and not ideal for development, where you would like to rerun one test that fail, and not run all 1000 others that are ok.
IntelliJ has options (UI) to run one test quickly, but this run python tests runner.
I add DJANGO_SETTINGS_MODULE=... inside, but now I get other errors:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I was looking to solve this error and I only found :
import django
django.setup()
inside Settings.py
My problem with this is:
I think this breaks normal behaviour of the app. App works normal for different environments.
It doesn't call code after this setup inside settings, so secret_key and others are not installed
This doesn't seam to be really related to tests, but is changing the whole app.
So, I am looking for some settings, how to set the normal python tests, so that they will run as django tests.
EDIT:
Now I change some thinks around and do:
Separate Settings for test
Do all the imports and then django.setup()
Now I get different error:
# The settings_test.py
SECRET_KEY = 'kdbaskdbkjadasd'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mobileapp',
]
DEBUG = True
ALLOWED_HOSTS = '*'
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',
]
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 = '...wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '...',
'USER': '...',
'PASSWORD': '...',
'HOST': 'localhost',
'PORT': 5432,
}
}
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
import django
django.setup()
error:
/Users/zadravecm/Work/.../env/bin/python3.6 /Users/zadravecm/Work/.../tests/tests.py
Traceback (most recent call last):
File "/Users/zadravecm/Work/.../tests/tests.py", line 2, in <module>
from ....Services import subsidiary_service as sub_service
File "/Users/zadravecm/Work/.../Services/subsidiary_service.py", line 3, in <module>
from ....models import *
File "/Users/zadravecm/Work/.../models.py", line 2, in <module>
from django.contrib.auth.models import User
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
class AbstractBaseUser(models.Model):
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/db/models/base.py", line 107, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/apps/registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/apps/registry.py", line 134, in check_apps_ready
settings.INSTALLED_APPS
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__
self._setup(name)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup
self._wrapped = Settings(settings_module)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/Users/zadravecm/Work/.../env/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Users/zadravecm/Work/.../settings_test.py", line 121, in <module>
django.setup()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate
app_config.ready()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready
self.module.autodiscover()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/Users/zadravecm/Work/.../env/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Users/zadravecm/.../env/lib/python3.6/site-packages/django/contrib/auth/admin.py", line 6, in <module>
from django.contrib.auth.forms import (
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 10, in <module>
from django.contrib.auth.models import User
ImportError: cannot import name 'User'
EDIT:
The image of the settings of a test runner that is run automatically, if I click run icon on tests.
I got the following error:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1741, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1735, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1135, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Apache24/htdocs/consult/accounts/models.py", line 7, in <module>
from django.contrib.auth.models import AbstractUser
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module>
class AbstractBaseUser(models.Model):
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\db\models\base.py", line 87, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\apps\registry.py", line 249, in get_containing_app_config
self.check_apps_ready()
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\apps\registry.py", line 131, in check_apps_ready
settings.INSTALLED_APPS
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\conf\__init__.py", line 57, in __getattr__
self._setup(name)
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\conf\__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\_pydevd_bundle\pydevd_xml.py", line 179, in _get_type
if isinstance(o, t[0]):
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\utils\functional.py", line 213, in inner
self._setup()
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\conf\__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I am very new to Python programming. Please help me to resolve this and let me know how to set PYTHON ENVIRONMENT VARIABLE.
this is my settings.py
INSTALLED_APPS =
[
'accounts',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_mysql',
]
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 = 'consult.urls'
TEMPLATES =
[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/templates/accounts/'],
'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 = 'consult.wsgi.application'
DATABASES =
{
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'suitecaredb',
'USER': 'root',
'PASSWORD': 'innovations',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'charset': 'utf8mb4',
},
'TEST': {
'CHARSET': 'utf8mb4',
'COLLATION': 'utf8mb4_unicode_ci',
}
}
}
AUTH_USER_MODEL = "accounts.User"
To open a python terminal with the Django environment set run
python manage.py shell
Then, for example, a new user can be created with the create_user() helper function:
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon#thebeatles.com', 'johnpassword')
# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name = 'Lennon'
>>> user.save()
The example code below shows how to add a user from a script. Note that you need to replace 'project.settings' on line 2 with your project name.
project.setting points at your project file where installed apps, middleware, templates, etc are specified.
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','project.settings')
import django
django.setup()
from django.contrib.auth.models import User
super_user = User.objects.create_user(username = 'john',
first_name = 'John',
last_name = 'Doe',
email = 'john.doe#mail.com',
password = 'test',
is_staff = True,
is_superuser=True
)
More information in the documentation docs.djangoproject.com
On setting:
wsgi.py
Check if it is pointing to the right setting path:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "path/to/settings.py")
Try out the following:
As mentioned in the above answer, ensure that the following line is present in wsgi.py
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "/path/to/settings.py")
Ensure that above path is correct or the mentioned settings file in above line is the actual settings file.
Since you are using Pycharm, the above error could because cause of some issue with the Pycharm environment variable. Try python manage.py flush.
If the issue still persists, have a look at the environment configuration in the Pycharm settings and check for any discrepancy.
I am able to execute
python manage.py migrate - it executes perfectly
But when I run
django-admin shell
it fails giving the following errors
Traceback (most recent call last):
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 337, in execute
saved_locale = translation.get_language()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 190, in get_language
return _trans.get_language()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__
if settings.USE_I18N:
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/cj/.vtenv/officingx/bin/django-admin", line 11, in <module>
sys.exit(execute_from_command_line())
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 306, in run_from_argv
connections.close_all()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 229, in close_all
for alias in self:
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 223, in __iter__
return iter(self.databases)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 156, in databases
self._databases = settings.DATABASES
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
My settings.py
"""
Django settings for officingx project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
import dj_database_url
# 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/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['OFFICINGX_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',
'amenity.apps.AmenityConfig',
'booking.apps.BookingConfig',
'location.apps.LocationConfig',
'organization.apps.OrganizationConfig',
'photo.apps.PhotoConfig',
'product.apps.ProductConfig',
'property.apps.PropertyConfig',
]
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 = 'officingx.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'officingx.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {'default': dj_database_url.config()}
# Password validation
# https://docs.djangoproject.com/en/1.10/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/1.10/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.10/howto/static-files/
STATIC_URL = '/static/'
Please help I can't understand why its not able read the settings even when migrate command is working perfectly fine
Taken from the docs:
Generally, when working on a single Django project, it’s easier to use manage.py than django-admin. If you need to switch between multiple Django settings files, use django-admin with DJANGO_SETTINGS_MODULE or the --settings command line option.
You didn't specify a --settings module (as an argument) in the django-admin, that's why Django complains. Do it like this: django-admin shell --settings=myproject.settings.
Also, from the docs:
The settings module should be in Python package syntax, e.g. mysite.settings. If this isn’t provided, django-admin will use the DJANGO_SETTINGS_MODULE environment variable.
You can also do ./manage.py shell