Related
I created my first with MongoDB with Django
while during the setup I am getting this problem error
Internal Server Error: /api/v1/device/
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 856, in parse
return handler(self, statement)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 928, in _insert
query.execute()
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 397, in execute
res = self.db[self.left_table].insert_many(docs, ordered=False)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/collection.py", line 761, in insert_many
blk.execute(write_concern, session=session)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 528, in execute
return self.execute_command(generator, write_concern, session)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 363, in execute_command
_raise_bulk_write_error(full_result)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 140, in _raise_bulk_write_error
raise BulkWriteError(full_result)
pymongo.errors.BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: farmos.device index: __primary_key__ dup key: { id: null }', 'keyPattern': {'id': 1}, 'keyValue': {'id': None}, 'op': {'device_id': 2, 'device_name': None, 'device_status': 'new', 'device_actions': True, 'device_token': True, '_id': ObjectId('63182c4ee9afd58ca7855029')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []}
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/cursor.py", line 56, in execute
params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 783, in __init__
self._query = self.parse()
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 868, in parse
raise exe from e
djongo.exceptions.SQLDecodeError:
Keyword: None
Sub SQL: None
FAILED SQL: INSERT INTO "device" ("device_id", "device_name", "device_status", "device_actions", "device_token") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s)
Params: [2, None, 'new', True, True]
Version: 1.3.3
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/cursor.py", line 59, in execute
raise db_exe from e
djongo.database.DatabaseError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/adarsh/farmos/farmos/persistance_layer/mongodb/device_operations.py", line 22, in create
serializer_user.save()
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/query.py", line 433, in create
obj.save(force_insert=True, using=self.db)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 784, in save_base
force_update, using, update_fields,
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 926, in _do_insert
using=using, raw=raw,
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1391, in execute_sql
cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/cursor.py", line 59, in execute
raise db_exe from e
django.db.utils.DatabaseError
directory-path
farmos
/device -> model,view,serializer
/farm -> model,view,serializer
/persistances_layer -> model,view,serializer
/farmos -> settings.py, urls.py, utils.py
here Is my settings.py file
please let m know if there is any mistake that I am making here
"""
Django settings for farmos project.
Generated by 'django-admin startproject' using Django 3.2.4.
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
# 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 = 'django-insecure-v-iu2x3pd&m0qap1k%y=8jua12v$adi*r132uha%&jdsp781(&'
# 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',
'rest_framework',
'rest_framework.authtoken',
'device.apps.DeviceConfig',
'farm.apps.FarmConfig',
'persistance_layer.apps.PersistanceLayerConfig'
]
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 = 'farmos.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 = 'farmos.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'farmos',
'CLIENT': {
'host': 'mongodb://srv13.absolute.ag:27017',
# 'username': 'user1',
# 'password': 'pass1',
# 'authSource': 'admin1',
# 'authMechanism': 'SCRAM-SHA-1',
}
}
}
# 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',
},
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'COERCE_DECIMAL_TO_STRING': False,
# 'EXCEPTION_HANDLER': 'farmos.utils.custom_exception_handler',
}
# 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'
here is the requirement.txt file packages that i am using
weasyprint~=52.5
boto3==1.10.41
django-3-jet==1.0.7
Django==3.2.4
django-cors-headers==3.7.0
django-extensions==2.2.3
django-filter==2.4.0
django-import-export==2.5.0
django-localflavor==2.2
django-phonenumber-field==3.0.1
django-rest-auth==0.9.5
django-simple-history==3.0.0
django-storages==1.8
djangorestframework==3.12.4
mysqlclient==2.0.3
phonenumbers==8.10.20
Pillow==8.2.0
requests==2.23.0
django-import-export==2.5.0
django-google-maps==0.12.4
drf-yasg==1.20.0
Flask==2.0.1
pandas==1.1.5
beautifulsoup4==4.9.3
slugify==0.0.1
django-taggit==1.3.0
PyMySQL==1.0.2
django-crontab==0.7.1
Werkzeug==2.0.2
numpy
python-dateutil==2.7.3
pytest==6.2.5
pytz==2019.3
jmespath==0.10.0
docutils==0.15.2
lxml==4.7.1
cffi==1.15.0
future==0.18.2
ipython==7.16.3
olefile==0.46
soupsieve==2.3.1
html5lib==1.1
httplib2==0.15.0
defusedxml==0.7.1
pip==21.3.1
keyring==18.0.1
PyYAML==5.3.1
Babel==2.9.1
botocore==1.13.50
s3transfer==0.2.1
MarkupSafe==2.0.1
Jinja2==3.0.3
click==8.0.3
blinker==1.4
itsdangerous==2.0.1
setuptools==45.2.0
sqlparse
asgiref==3.4.1
colorama==0.4.3
py==1.11.0
python-stdnum==1.17
tablib==3.1.0
xlrd==2.0.1
xlwt==1.3.0
MarkupPy==1.14
openpyxl==3.0.9
certifi==2019.11.28
chardet==3.0.4
itypes==1.2.0
coreapi==2.3.3
coreschema==0.0.4
uritemplate==4.1.1
cryptography==2.8
urllib3==1.25.8
simplejson==3.16.0
coverage==6.2
six==1.14.0
Pygments==2.10.0
inflection==0.5.1
idna==2.8
paramiko==2.6.0
pyparsing==3.0.6
google_api_python_client==2.42.0
oauth2client==4.1.3
ua-parser==0.10.0
user-agents==2.2.0
django-user-agents==0.4.0
django_db_logger
dataclasses==0.1
djongo==1.3.3
pymongo==3.11.2
djangotoolbox>=1.6.0
django-dbindexer>=1.6.0
gunicorn==19.9.0
django-crispy-forms==1.9.0
dnspython==1.16.0
For dealing with module named Djongo for connecting Django with MongoDb , one should be completely aware of the modules versions being used in the environment.
Make sure your using the library versions stated below.
asgiref==3.5.0,
Django==4.0.3,
djongo==1.3.6,
dnspython==2.2.1,
pykerberos==1.2.4,
pymongo==3.12.1,
python-snappy==0.6.1,
pytz==2022.1,
sqlparse==0.2.4,
configure the Database settings in the settings.py. Its not necessary to use host while connnecting to the localhost of MongoDb.
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'your-db-name',
}
}
Premise: I'm a starter[Plz be kind and patient]
When i try to run commands in the terminal like:
python manage.py makemigrations audioma_manager
or
python manage.py runserver
or
python manage.py migrate
or
python manage.py --run-syncdb
where
audioma_manager is the name of my project
I tried also with the name of my app
I get this excetion code, I searched lots on the net but any kind of solution works with my problem:
Traceback (most recent call last):
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_session
The above exception was the direct cause of the following exception:
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\39371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle
self.check(databases=[database])
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 423, in check
databases=databases,
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\39371\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\39371\audioma_manager\audioma_manager\urls.py", line 20, in <module>
path('transcription_form/', include('transcription_form.urls')),
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\39371\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\39371\audioma_manager\transcription_form\urls.py", line 2, in <module>
from .views import upload
File "C:\Users\39371\audioma_manager\transcription_form\views.py", line 4, in <module>
from .forms import UploadForm
File "C:\Users\39371\audioma_manager\transcription_form\forms.py", line 5, in <module>
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
File "C:\Users\39371\audioma_manager\transcription_form\client_transcpition_api.py", line 48, in call_api
session_stored = s.load()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load
s = self._get_session_from_db()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 34, in _get_session_from_db
expire_date__gt=timezone.now()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 431, in get
num = len(clone)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 262, in __len__
self._fetch_all()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_session
This is my setting file( I'm using django-environ to keep secret some variables):
import environ
import os
from pathlib import Path
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
DJANGO_SETTINGS_MODULE="audioma_manager.settings"
# Set the project base directory
BASE_DIR = Path(__file__).resolve().parent.parent
# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
# False if not in os.environ because of casting above
DEBUG = env('DEBUG')
# Raises Django's ImproperlyConfigured
# exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
# Parse database connection url strings
# like psql://user:pass#127.0.0.1:8458/db
#For production
#DATABASES = {
# read os.environ['DATABASE_URL'] and raises
# ImproperlyConfigured exception if not found
#
# The db() method is an alias for db_url().
'default': env.db(),
# read os.environ['SQLITE_URL']
#'extra': env.db_url(
#'SQLITE_URL',
#default='sqlite:///tmp/my-tmp-sqlite.db'
# )
#}
CACHES = {
# Read os.environ['CACHE_URL'] and raises
# ImproperlyConfigured exception if not found.
#
# The cache() method is an alias for cache_url().
'default': env.cache(),
#instance of sensibile data from .env file
}
API_URL= {
env('API_URL')
}
API_VERSION={
env('API_VERSION')
}
API_USERNAME={
env('API_USERNAME')
}
API_PASSWORD={
env('API_PASSWORD')
}
API_ENDPOINT_SOURCES={
env('API_ENDPOINT_SOURCES')
}
DEFAULT_DIR_PATH={
env('DEFAULT_DIR_PATH')
}
DEFAULT_NAME_FILE_PATTERN={
env('DEFAULT_NAME_FILE_PATTERN')
}
API_ENDPOINT_LOGIN={
env('API_ENDPOINT_LOGIN')
}
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'transcription_form',
'corsheaders',
'rest_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',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware'
]
ROOT_URLCONF = 'audioma_manager.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 = 'audioma_manager.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
#Local db for tests
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'USER': 'USER',
'PASSWORD': 'PASS',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
# 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',
},
]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': '\\Users\\39371\\audioma_manager\\audioma_manager\\logs\\debug.log',
},
},
'loggers': {
'transcription_form.client_transcription_api': {
'handlers': ['file'],
'level': 'INFO'
},
},
}
# 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'
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http://localhost:8080',
)
My client:
from audioma_manager.settings import API_ENDPOINT_LOGIN, API_PASSWORD, API_URL, API_USERNAME, API_VERSION
from django.contrib.sessions.backends.db import SessionStore
import requests
from requests.structures import CaseInsensitiveDict
#class API management
class GetAPISources:
#authentication to aziendal api
def auth_api(self):
url = API_URL + API_VERSION + API_ENDPOINT_LOGIN
auth_email = API_USERNAME
auth_password = API_PASSWORD
list_of_auth = [auth_email,auth_password]
response= requests.post(url,list_of_auth)
if response.status_code==400:
#manage exception code; return null
return False
token=response['token']
#instance of SessionStore
s=SessionStore()
s['auth_token']=token
# saves the current token
s.save()
#implement a method who calls API endpoint from InfojuiceAPi with representation=1
def call_api(self,endpoint):
api_repr='&representation=1'
s=SessionStore()
session_stored = s.load()
auth_token=session_stored['auth_token']
#used endpoint so i can customize the type of endpoint everytime i call the function
#example--> endpoint='/sources' ; endpoint='/customers'
url = API_URL + API_VERSION + endpoint + api_repr
headers = CaseInsensitiveDict()
headers["Accept"]="application/json"
headers["Authorization"]="token " + auth_token
response= requests.get(url,headers=headers)
if response.status_code==401:
self.auth_api()
self.call_api(endpoint)
return response
My Model:
from django.db import models
# Create your models here.
class Transcription(models.Model):
id = models.BigAutoField
file_name = models.CharField(max_length=10000)
created_at = models.DateTimeField(auto_now_add=True, name='created_at')
updated_at = models.DateTimeField(auto_now=True, name='updated_at')
def __str__(self):
return self.file_name
My Form:
from django import forms
from .client_transcpition_api import GetAPISources
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
class UploadForm(forms.Form):
lang = forms.CharField(label='Lingua', max_length=100, help_text = "Inserisci la lingua del contenuto")
source = forms.CharField(label='Fonte', help_text = "Seleziona la fonte del contenuto" , widget=forms.Select(choices=source_choice))
data = forms.DateField(label='data', help_text = "Seleziona la data del contenuto ", max_length=100)
time = forms.TimeField(label='ora', help_text = "Seleziona l' orario del contenuto", max_length=100)
extension = forms.CharField(label='estensione', help_text = "Seleziona l'estensione del contenuto", max_length=100)
file = forms.FileField(label='file da caricare', help_text = "Seleziona il file da mandare in trascrizione")
My views:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadForm
def upload(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = UploadForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# redirect to a new URL:
#this url is only temp, evaluate better how to do
return HttpResponseRedirect('/thanks/')
else:
form = upload()
return render(request, 'upload.html', {'form': form})
My template:
<!DOCTYPE html>
{% Block Content %}
<h2>Upload</h2>
<form enctype="multipart/form-data" method="post" action="/foo/">
<!-- we need to use this token bc Django makes security controls and requires this token
to be recognize as trust source of code -->
{% csrf_token %}
{{form}}
<input type="file" name="recupero">
<button type="submit">Invio</button>
</form>
In my project I want to:
1)Create repositories, new Django project and first commit.
2)Install Django Environ to upload configurations via .env files.
The configuration must allow you to configure:
authentication to Aziendal API (URL, version, username, password)
path directory for saving the new file to be transcribed
filename pattern (with placeholder for replacing the various components, such as date, source name, title, language, time)
3)Create the Transcription model to save information about content sent in transcription.
Scheme:
ID
file_name Method (String)
created_at (Datetime)
updated_at (Datetime)
4)
Implement a mini client to Aziendal API for THE GET retrieval of sources filtered by name and with the query parameter for rapresentation retrieval.
Use the authentication configured in the configuration file.
5)
Implement a page with a form to load a new transcript with the following fields:
date (date)
source (select sources taken from API)
language (select taken from the configuration)
title
possible profile (optional)
Plz help a young starter.
If u need some source code of my project, just ask:)
Thx for help
xoxo
The most pressing problem here is that you're doing a database call at import time by trying to load a session via
File "C:\Users\39371\audioma_manager\transcription_form\forms.py", line 5, in <module>
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
File "C:\Users\39371\audioma_manager\transcription_form\client_transcpition_api.py", line 48, in call_api
session_stored = s.load()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load
s = self._get_session_from_db()
which is a big no-no in Django and leads to a chicken-and-egg problem:
you need to make migrations and run migrations to create database tables
Django needs to be able to import your app to do so
your app tries to do a database query from an as-of-yet-nonexistent table (since it's not been migrated yet).
You'll need to do that source_choice at e.g. __init__ time for the form, not at import time.
For the time being, you can replace the source_choice=... line with just source_choice=[] – you won't have any sources to choose from, but you can get your migrations running.
That aside, that session-related code looks strange, especially since you're trying to do so outside of a request context. There will be no valid session to load in that case, since there is no request either. I think you may be confusing Django sessions with whatever the API you're using requires.
I encountered an issue while migrating a DB using django:
Traceback (most recent call last): File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "myBlog_category" does not
exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM
"myBlog_ca...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "manage.py", line 22, in
main() File "manage.py", line 18, in main
execute_from_command_line(sys.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py",
line 401, in execute_from_command_line
utility.execute() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py",
line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 330, in run_from_argv
self.execute(*args, **cmd_options) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 368, in execute
self.check() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 392, in check
all_issues = checks.run_checks( File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py",
line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 13, in check_url_config
return check_resolver(resolver) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 23, in check_resolver
return check_method() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 408, in check
for pattern in self.url_patterns: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 582, in urlconf_module
return import_module(self.urlconf_name) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File
"", line 991, in _find_and_load File
"", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in
exec_module File "", line 219, in
call_with_frames_removed File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\blog\urls.py", line 8, in
path('', include('myBlog.urls')), File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\conf.py",
line 34, in include
urlconf_module = import_module(urlconf_module) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File
"", line 991, in _find_and_load File
"", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in
exec_module File "", line 219, in
_call_with_frames_removed File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\urls.py", line 2,
in
from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView,
CategoryListView, LikeView, AddCommentView File
"C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\views.py", line 4,
in
from .forms import PostForm, EditForm, CommentForm File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\forms.py", line 6,
in
for item in choices: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 287, in iter
self._fetch_all() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 1303, in _fetch_all
self._result_cache = list(self._iterable_class(self)) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 142, in iter
return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1108, in results_iter
results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1156, in execute_sql
cursor.execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 98, in execute
return super().execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 75, in _execute_with_wrappers
return executor(sql, params, many, context) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py",
line 90, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "myBlog_category" does not
exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM
"myBlog_ca...
I deployed the app to heroku and got errors so I tried to change the sqlite db to psql before commiting it to heroku but after doing this tutorial migrations did not work anymore, I got stuck on the 3rd step of the tutorial.
I tried the following:
Delete migrations folder from myBlog
Delete db.sqlite3 file
After removing the files/folders above I tried python manage.py makemigrations and got the following error:
Traceback (most recent call last):
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "myBlog_category" does not exist
LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca...
^
The above exception was the direct cause of the following exception:
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\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py",
line 401, in execute_from_command_line
utility.execute()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py",
line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 368, in execute
self.check()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 392, in check
all_issues = checks.run_checks(
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py",
line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 23, in check_resolver
return check_method()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 408, in check
for pattern in self.url_patterns:
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 582, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1014, in _gcd_import
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in exec_module
File "", line 219, in call_with_frames_removed
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\blog\urls.py", line 8, in
path('', include('myBlog.urls')),
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\conf.py",
line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1014, in _gcd_import
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in exec_module
File "", line 219, in _call_with_frames_removed
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\urls.py", line 2,
in
from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView,
CategoryListView, LikeView, AddCommentView
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\views.py", line 4,
in
from .forms import PostForm, EditForm, CommentForm
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\forms.py", line 6,
in
for item in choices:
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 287, in iter
self._fetch_all()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 1303, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 142, in iter
return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1108, in results_iter
results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1156, in execute_sql
cursor.execute(sql, params)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 98, in execute
return super().execute(sql, params)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py",
line 90, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "myBlog_category" does not exist
LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca...
Trying to run the server locally now, doesn't work.
While deploying it to heroku I got ProgrammingError - something close to what I get now. I tried to run:
heroku run python manage.py migrate
But got the app would return me the same error as the same traceback at the begging of the post.
My settings.py file:
"""
Django settings for blog 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/
"""
import os
import django_heroku
import dj_database_url
from decouple import config
from pathlib import Path
# 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 = 'django-insecure-97gr5qi*888x%%n!=yp(uf*xz!8(jucnfd!ln+_zkyg#8#e5th'
# 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',
'myBlog',
'members',
'ckeditor',
]
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 = 'blog.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 = 'blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.postgresql_psycopg2',
'NAME' : 'my_db',
'USER' : 'hero',
'PASSWORD' : 'my_db # 123',
'HOST' : 'localhost',
'PORT' : '5432',
}
}
# 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/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
django_heroku.settings(locals())
For any other additional required informations please let me know.
Edit 1:
My models.py
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self) :
return self.name
def get_absolute_url(self) :
return reverse('home')
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bio = models.TextField()
profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile")
website_url = models.CharField(max_length=255, null=True, blank=True)
facebook_url = models.CharField(max_length=255, null=True, blank=True)
instagram_url = models.CharField(max_length=255, null=True, blank=True)
twitter_url = models.CharField(max_length=255, null=True, blank=True)
pinterest_url = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return str(self.user)
def get_absolute_url(self) :
return reverse('home')
class Post(models.Model):
title = models.CharField(max_length=255)
header_image = models.ImageField(null=True, blank=True, upload_to="images/")
title_tag = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='uncategorized')
snippet = models.CharField(max_length=255)
likes = models.ManyToManyField(User, related_name='blog_posts')
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
# Create your models here.
def get_absolute_url(self):
return reverse('article-detail', args=(str(self.id),))
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.CharField(max_length=255)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
views.py for myBlog app:
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, Category, Comment
from .forms import PostForm, EditForm, CommentForm
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator
# Create your views here.
def LikeView(request, pk):
post = Post.objects.get(id=pk)
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return HttpResponseRedirect(reverse('article-detail', args=[str(pk)]))
class HomeView(ListView):
model = Post
template_name = 'home.html'
ordering = ['-post_date']
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(HomeView, self).get_context_data(*args, **kwargs)
context["cat_menu"] = cat_menu
return context
class ArticleDetailView(DetailView):
model = Post
template_name = 'article_details.html'
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)
stuff = get_object_or_404(Post, id=self.kwargs['pk'])
liked = False
if stuff.likes.filter(id=self.request.user.id).exists():
liked = True
total_likes = stuff.total_likes()
context["cat_menu"] = cat_menu
context["total_likes"] = total_likes
context["liked"] = liked
return context
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
def CategoryListView(request):
cat_menu_list = Category.objects.all()
return render(request, 'category_list.html', {'cat_menu_list': cat_menu_list})
def CategoryView(request, cats):
category_posts = Post.objects.filter(category=cats.title().replace('-', ' '))
return render(request, 'categories.html', {'cats': cats.title().replace('-', ' '), 'category_posts': category_posts})
class AddCategoryView(CreateView):
model = Category
fields = '__all__'
template_name = 'add_category.html'
class UpdatePostView(UpdateView):
model = Post
template_name = 'update_post.html'
form_class = EditForm
class DeletePostView(DeleteView):
model = Post
template_name = 'delete_post.html'
success_url = reverse_lazy('home')
class AddCommentView(CreateView):
model = Comment
form_class = CommentForm
template_name = 'add_comment.html'
def form_valid(self, form):
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
success_url = reverse_lazy('home')
You shouldn't have deleted the migrations folder. Add this folder to your application and add the init file to it. Then create migrations locally. You have to create migrations locally. Heroku should not (and will not) create migration files. Heroku is just executing your code.
Also, if the data in the database is not important, you can re-create db to update the migration table. Or you can update it manually.
Steps
1. Creating a migration folder
cd ./your_app
mkdir migrations
cd migrations
touch __ini__.py
2. Creating migrations
./manage.py makemigrations
3. Pushing on heroku
4. Applying migrations
heroku run python manage.py migrate
P.S: I think Heroku has the tools to manage the Django app. Please refer to the documentation. I think applying migrations should be automatic.
You should performing steps 1-3 locally.
You can re-create the database on heroku or reset it. If you are re-creating the database, do not forget to change the access parameters in the project settings
I tried to delete the migrations folder and db.sqlite3 as suggestions but it didn't work. I've also tried to downgrade version of django. Please look at the error below, I think it's the problem with database :
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "c:\python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Admin\Downloads\store2\Django-E-Commerce-master\user\models.py", line 8, in <module>
from home.models import Language
File "C:\Users\Admin\Downloads\store2\Django-E-Commerce-master\home\models.py", line 21, in <module>
for rs in llist:
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 268, in __iter__
self._fetch_all()
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 54, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\sql\compiler.py", line 1065, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "home_language" does not exist
LINE 1: ...ge"."create_at", "home_language"."update_at" FROM "home_lang...
This is setting file,
import os
from django.utils.translation import gettext_lazy as _
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!l3!x0w-(f39+(#*a3a^8p#gf+o66e(#c#w1u13u*0=#-qpxbn'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'user.apps.UserConfig',
'order.apps.OrderConfig',
'product.apps.ProductConfig',
'home.apps.HomeConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ckeditor',
'mptt',
'currencies',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'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',
'currencies.context_processors.currencies'
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGES = [
('en', _('English')),
('tr', _('Turkish')),
]
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
DEFAULT_CURRENCY = 'USD'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
# ...
SITE_ID = 1
####################################
## CKEDITOR CONFIGURATION ##
####################################
CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'
CKEDITOR_UPLOAD_PATH = 'images/'
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_CONFIGS = {
'default': {
'toolbar': None,
},
}
###################################
#APPEND_SLASH=False
This is the model part where it is printing out the error :
class Language(models.Model):
name= models.CharField(max_length=20)
code= models.CharField(max_length=5)
status=models.BooleanField()
create_at=models.DateTimeField(auto_now_add=True)
update_at=models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
llist = Language.objects.filter(status=True)
list1 = []
for rs in llist:
list1.append((rs.code,rs.name))
langlist = (list1)
I think there's something wrong with this part of model.py since it throws out same error when I delete everything and leave only this part in models.py
I think the cause is this line llist = Language.objects.filter(status=True)
I keep getting this traceback
(pythonApp) D:\task_trackv2>python manage.py makemigrations
D:\task_trackv2\apps_config\settings.py
D:\pythonApp\lib\site-packages\environ\environ.py:637: UserWarning: Error reading .env.local - if you're not configuring your environment separately, check this.
warnings.warn(
D:\task_trackv2\apps_config\settings.py
D:\task_trackv2\apps_config\settings.py
Traceback (most recent call last):
File "D:\pythonApp\lib\site-packages\environ\environ.py", line 273, in get_value
value = self.ENVIRON[var]
File "c:\users\belkin\appdata\local\programs\python\python38-32\lib\os.py", line 675, 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 "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "D:\pythonApp\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "D:\pythonApp\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 366, in execute
self.check()
File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = self._run_checks(
File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
return checks.run_checks(**kwargs)
File "D:\pythonApp\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\pythonApp\lib\site-packages\django\core\checks\translation.py", line 60, in check_language_settings_consistent
get_supported_language_variant(settings.LANGUAGE_CODE)
File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__
self._setup(name)
File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 63, in _setup
self._wrapped = Settings(settings_module)
File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 142, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "c:\users\belkin\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\task_trackv2\apps_config\settings.py", line 38, in <module>
SECRET_KEY = env('SECRET_KEY')
File "D:\pythonApp\lib\site-packages\environ\environ.py", line 123, in __call__
return self.get_value(var, cast=cast, default=default, parse_default=parse_default)
File "D:\pythonApp\lib\site-packages\environ\environ.py", line 277, in get_value
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
I don't really know what's the issue here, maybe there's something I'm missing due to the fact that I'm working in a venv, but I can't be certain. On the django-environ docs page it says that this error would occur if SECRET_KEY isn't set in os.environ, but setting it through the python console gave no effect
this is my settings.py:
import environ
from typing import List
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
environ.Env.read_env(env_file='.env.local')
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DEBUG')
ALLOWED_HOSTS: List[str] = ['*']
AUTH_USER_MODEL = 'user.User'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'apps.base',
'apps.user',
'apps.team',
'apps.notes',
'apps.invite'
]
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 = 'apps_config.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 = 'apps_config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/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.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
and this is my .env.local file (same location as settings.py):
DEBUG=True
SECRET_KEY='8x0=1jo1b-db5tz%f=q%)j8%4y(^_b0g9w#0+ugu(#i-u2d!1'
DB_NAME='task_trackv2'
DB_USER='task_track'
DB_PASSWORD='1234'
DB_HOST='localhost'
DB_PORT='5432'
Below instruction was how I solve this problem in my project.
In the .env file, the secret key should be SECRET_KEY=generate_secret_key.
And in the settings.py the lineSECRET_KEY = env('SECRET_KEY') should be SECRET_KEY = env.str('SECRET_KEY', 'sample_unsafe_secret').
In the settings.py file, the line SECRET_KEY = env('SECRET_KEY') should be SECRET_KEY = env('SECRET_KEY', 'sample_secret')
If you do not specify the default value for your environment variable, you get the ImproperlyConfigured error.
You must not use quotations in .env file. How it must be:
DEBUG=True
SECRET_KEY=8x0=1jo1b-db5tz%f=q%)j8%4y(^_b0g9w#0+ugu(#i-u2d!1
DB_NAME=task_trackv2
DB_USER=task_track
DB_PASSWORD=1234
DB_HOST=localhost
DB_PORT=5432
Defining default value is an option but that is for the time that you don't or you can't use the .env file. So as soon as you want to use environ file, you need to configure the file well to receive all the values.
Anyway defining default value is like this:
SECRET_KEY = env("SECRET_KEY", default="unsafe-secret-key")
I think the problem is in your file path. You can set your path on any of these below methods.
env.read_env(BASE_DIR('.env'))
env.read_env(os.path.join(BASE_DIR, '.env'))
env.read_env(pathlib.Path(str(BASE_DIR)).joinpath('.env'))
env.read_env(pathlib.Path(str(BASE_DIR)) / '.env')
you can refer to more on django-environ