Django settings not working correctly - python

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

Related

("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'asgi'

My settings.py file:
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 2.2.13.
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 = 'af^zgg5*t&h)3dghcvd#9o1#st9b(bgh#5a32%m%!g38u(tl!f'
# 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',
'chat',
'channels',
]
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 = 'myproject.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 = 'myproject.wsgi.application'
ASGI_APPLICATION = 'asgi.application'
# 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'),
}
}
# 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/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
And my asgi.py:
"""
ASGI config for myproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = ProtocolTypeRouter({
'http': get_asgi_application()
})
Error:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
June 02, 2022 - 07:12:02
Django version 3.0, using settings 'myproject.settings'
Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\routing.py", line 28, in get_default_application
module = importlib.import_module(path)
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'asgi'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\management\commands\runserver.py", line 107, in inner_run
application=self.get_application(options),
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\manag
unserver.py", line 132, in get_application
return StaticFilesWrapper(get_default_application())
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\routi
in get_default_application
raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'asgi'
i have updated my django from 2.2 to 3.0 but the problem don't go please do something
and the asgi.py file was created by me
just want the server to recognize the routing application and start working
I've followed the channels 2 tutorial, but I'm getting this error after runningI've followed the channels 2 tutorial, but I'm getting this error after runningI've followed the channels 2 tutorial, but I'm getting this error after running
# WSGI_APPLICATION = 'myproject.wsgi.application'
ASGI_APPLICATION = 'asgi.application'
Note how the WSGI example also has the project name? I suspect you need to include projectname in the setting, eg,
ASGI_APPLICATION = 'projectname.asgi.application'
The channels docs seems to support this format (https://channels.readthedocs.io/en/stable/installation.html)

Django RestAPI but without CSS

I am making an REST API using Django Restframework
It works perfectly but I get an error when I have pushed it to railway app like this
Installing SQLite3
-----> $ python manage.py collectstatic --noinput
Traceback (most recent call last):
File "/workspace/manage.py", line 22, in <module>
main()
File "/workspace/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle
collected = self.collect()
File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect
handler(path, prefixed_path, storage)
File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file
if not self.delete_file(path, prefixed_path, source_storage):
File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file
if self.storage.exists(prefixed_path):
File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 318, in exists
return os.path.exists(self.path(name))
File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 38, in path
raise ImproperlyConfigured("You're using the staticfiles app "
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
! Error while running '$ python manage.py collectstatic --noinput'.
See traceback above for details.
You may need to update application code to resolve this error.
Or, you can disable collectstatic for this application:
$ heroku config:set DISABLE_COLLECTSTATIC=1
https://devcenter.heroku.com/articles/django-assets
ERROR: failed to build: exit status 1
ERROR: failed to build: executing lifecycle: failed with status code: 145
Here is the settings.py file
"""
Django settings for crm_project 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
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 = os.getenv('DEBUG')
ALLOWED_HOSTS = [
'boss-instrument-production.up.railway.app', '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', # new
'customer', # new
]
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 = 'crm_project.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 = 'crm_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.getenv('PGDATABASE'),
'USER': os.getenv('PGUSER'),
'PASSWORD': os.getenv('PGPASSWORD'),
'HOST': os.getenv('PGHOST'),
'PORT': os.getenv('PGPORT'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
I tried resolving it by adding the DISABLE_COLLECTSTATIC variable with 1 as a value as one of the env variables. It works then, but the CSS in the API pages is gone
So can anyone let me know what I can do to get rid of this error and get the CSS onto the website?
You should get advantage of a tool such as WhiteNoise to setup the Django static files configuration for production. I think you are using Heroku, for this reason I just attached here a sample configuration for the Django settings.py file that should work for you.
PS: remind that Django doesn't handle your static files anymore when you set DEBUG=False
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# and here the rest of your settings
# ...
# Static files configuration
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = os.path.join(BASE_DIR, 'static/')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
# ...
# Loading test/prod settings based on ENV settings
ENV = os.environ.get('ENV')
# Add this part to the production environment only
# (Heroku in this case) with DEBUG=False:
try:
from .production_settings import *
MIDDLEWARE.append('whitenoise.middleware.WhiteNoiseMiddleware',)
except ImportError:
pass

Django settings module exception

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.

Django exception on server start up - module not found

I have searched online for other solutions with little luck. Posting here is a last resort.
Everything was working well with my Django project. Then suddenly it stopped running the server as it used to. I'm not sure at all what I have done wrong.
The issue is persistent across all of the git branches (it wasn't like this before) - making it even more confusing as the problem is not isolated to my branch only.
Here is the error traceback:
WARNINGS:
?: (1_7.W001) MIDDLEWARE_CLASSES is not set.
HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. If your project needs these middleware then you should configure this setting.
System check identified 1 issue (0 silenced).
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001A7227EB598>
Traceback (most recent call last):
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\utils\autoreload.py", line 229, in wrapper
fn(*args, **kwargs)
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\core\management\commands\runserver.py", line 116, in inner_run
self.check_migrations()
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\core\management\commands\runserver.py", line 168, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\executor.py", line 19, in __init__
self.loader = MigrationLoader(self.connection)
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\loader.py", line 47, in __init__
self.build_graph()
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\loader.py", line 185, in build_graph
self.load_disk()
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\loader.py", line 103, in load_disk
migration_module = import_module("%s.%s" % (module_name, migration_name))
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\connect_therapy\migrations\0021_auto_20180313_1946.py", line 4, in <module>
import django.contrib.auth.base_user
ModuleNotFoundError: No module named 'django.contrib.auth.base_user'
Also, note that I tried changing to MIDDLEWARE_CLASSES [...] in settings.py - but it didnt help.
Here is settings.py:
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True # should be true unless doing test on local network
ALLOWED_HOSTS = ['*'] # should be [] unless doing test on local network (then it should be ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'co.apps.CTherapyConfig',
"sslserver",
]
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 = '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.11/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.11/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',
},
]
# This must be changed for production
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
TWILIO_PHONE_NUMBER = '+number'
TWILIO_ACC_SID = 'key'
TWILIO_AUTH_TOKEN = 'token'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
Any ideas/suggestions are welcome.
Just to reiterate. This came out of the blue. No idea what caused it.
Thank you.
It came out because something changed in your project and a migration now fails.
In the error log you can see
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\connect_therapy\migrations\0021_auto_20180313_1946.py", line 4, in <module>
import django.contrib.auth.base_user
ModuleNotFoundError: No module named 'django.contrib.auth.base_user'
What that migration does? Is still valid or the project is changed and the migration try to load resources that are not anymore available?
If you run python manage.py shell are you able to import from 'django.contrib.auth.base_user'? The problem seems to be in that migration
The 'solution' at the end was to just make a new virtual environment. For some reason the old one messed up.

not able to run manage.py runserver

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.

Categories