I’m making website using Python Framework of ‘Django’.
I have some problems with Django about secret_key .
When I set a secret_key in .env file on private and change settings.py, there is problem.
I’m trying to solve it by myself, but its so difficult.
When I runserver on django, It errors contain:
JavaScript
x
62
62
1
(venv) C:pragmatic>python manage.py runserver
2
C:pragmaticvenvlibsite-packagesenvironenviron.py:637: UserWarning: Error reading C:
3
pragmatic.env - if you're not configuring your environment separately, check this.
4
warnings.warn(
5
Traceback (most recent call last):
6
File "C:pragmaticvenvlibsite-packagesenvironenviron.py", line 273, in get_value
7
value = self.ENVIRON[var]
8
File "C:UsersPJJAppDataLocalProgramsPythonPython38-32libos.py", line 675, in __
9
getitem__
10
raise KeyError(key) from None
11
KeyError: 'SECRET_KEY'
12
13
During handling of the above exception, another exception occurred:
14
15
Traceback (most recent call last):
16
File "manage.py", line 22, in <module>
17
main()
18
File "manage.py", line 18, in main
19
execute_from_command_line(sys.argv)
20
File "C:pragmaticvenvlibsite-packagesdjangocoremanagement__init__.py", line 401,
21
in execute_from_command_line
22
utility.execute()
23
File "C:pragmaticvenvlibsite-packagesdjangocoremanagement__init__.py", line 395,
24
in execute
25
self.fetch_command(subcommand).run_from_argv(self.argv)
26
File "C:pragmaticvenvlibsite-packagesdjangocoremanagementbase.py", line 330, in
27
run_from_argv
28
self.execute(*args, **cmd_options)
29
File "C:pragmaticvenvlibsite-packagesdjangocoremanagementcommandsrunserver.py",
30
line 61, in execute
31
super().execute(*args, **options)
32
File "C:pragmaticvenvlibsite-packagesdjangocoremanagementbase.py", line 371, in
33
execute
34
output = self.handle(*args, **options)
35
File "C:pragmaticvenvlibsite-packagesdjangocoremanagementcommandsrunserver.py",
36
line 68, in handle
37
if not settings.DEBUG and not settings.ALLOWED_HOSTS:
38
File "C:pragmaticvenvlibsite-packagesdjangoconf__init__.py", line 83, in __getatt
39
r__
40
self._setup(name)
41
File "C:pragmaticvenvlibsite-packagesdjangoconf__init__.py", line 70, in _setup
42
self._wrapped = Settings(settings_module)
43
File "C:pragmaticvenvlibsite-packagesdjangoconf__init__.py", line 177, in __init_
44
_
45
mod = importlib.import_module(self.SETTINGS_MODULE)
46
File "C:UsersPJJAppDataLocalProgramsPythonPython38-32libimportlib__init__.py",
47
line 127, in import_module
48
return _bootstrap._gcd_import(name[level:], package, level)
49
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
50
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
51
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
52
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
53
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
54
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
55
File "C:pragmaticpragmaticsettings.py", line 33, in <module>
56
SECRET_KEY = env('SECRET_KEY')
57
File "C:pragmaticvenvlibsite-packagesenvironenviron.py", line 123, in __call__
58
return self.get_value(var, cast=cast, default=default, parse_default=parse_default)
59
File "C:pragmaticvenvlibsite-packagesenvironenviron.py", line 277, in get_value
60
raise ImproperlyConfigured(error_msg)
61
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
62
settings.py contains:
JavaScript
1
133
133
1
"""
2
Django settings for pragmatic project.
3
4
Generated by 'django-admin startproject' using Django 3.1.4.
5
6
For more information on this file, see
7
https://docs.djangoproject.com/en/3.1/topics/settings/
8
9
For the full list of settings and their values, see
10
https://docs.djangoproject.com/en/3.1/ref/settings/
11
"""
12
13
from pathlib import Path
14
15
import os, environ
16
env = environ.Env(
17
# set casting, default value
18
DEBUG=(bool, False)
19
)
20
21
# Build paths inside the project like this: BASE_DIR / 'subdir'.
22
BASE_DIR = Path(__file__).resolve().parent.parent
23
24
# reading .env file
25
environ.Env.read_env(
26
env_file = os.path.join(BASE_DIR, '.env')
27
)
28
29
# Quick-start development settings - unsuitable for production
30
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
31
32
# SECURITY WARNING: keep the secret key used in production secret!
33
SECRET_KEY = env('SECRET_KEY')
34
35
# SECURITY WARNING: don't run with debug turned on in production!
36
DEBUG = True
37
38
ALLOWED_HOSTS = []
39
40
41
# Application definition
42
43
INSTALLED_APPS = [
44
'django.contrib.admin',
45
'django.contrib.auth',
46
'django.contrib.contenttypes',
47
'django.contrib.sessions',
48
'django.contrib.messages',
49
'django.contrib.staticfiles',
50
'accountapp',
51
52
]
53
54
MIDDLEWARE = [
55
'django.middleware.security.SecurityMiddleware',
56
'django.contrib.sessions.middleware.SessionMiddleware',
57
'django.middleware.common.CommonMiddleware',
58
'django.middleware.csrf.CsrfViewMiddleware',
59
'django.contrib.auth.middleware.AuthenticationMiddleware',
60
'django.contrib.messages.middleware.MessageMiddleware',
61
'django.middleware.clickjacking.XFrameOptionsMiddleware',
62
]
63
64
ROOT_URLCONF = 'pragmatic.urls'
65
66
TEMPLATES = [
67
{
68
'BACKEND': 'django.template.backends.django.DjangoTemplates',
69
'DIRS': [],
70
'APP_DIRS': True,
71
'OPTIONS': {
72
'context_processors': [
73
'django.template.context_processors.debug',
74
'django.template.context_processors.request',
75
'django.contrib.auth.context_processors.auth',
76
'django.contrib.messages.context_processors.messages',
77
],
78
},
79
},
80
]
81
82
WSGI_APPLICATION = 'pragmatic.wsgi.application'
83
84
85
# Database
86
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
87
88
DATABASES = {
89
'default': {
90
'ENGINE': 'django.db.backends.sqlite3',
91
'NAME': BASE_DIR / 'db.sqlite3',
92
}
93
}
94
95
96
# Password validation
97
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
98
99
AUTH_PASSWORD_VALIDATORS = [
100
{
101
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
102
},
103
{
104
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
105
},
106
{
107
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
108
},
109
{
110
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
111
},
112
]
113
114
115
# Internationalization
116
# https://docs.djangoproject.com/en/3.1/topics/i18n/
117
118
LANGUAGE_CODE = 'en-us'
119
120
TIME_ZONE = 'UTC'
121
122
USE_I18N = True
123
124
USE_L10N = True
125
126
USE_TZ = True
127
128
129
# Static files (CSS, JavaScript, Images)
130
# https://docs.djangoproject.com/en/3.1/howto/static-files/
131
132
STATIC_URL = '/static/'
133
.env contains:
JavaScript
1
7
1
DEBUG=on
2
SECRET_KEY=o$6-&b%^ww2_+^euxx!=@g7a$j)ef4v(x_z(ojrkhgv=j2b)$_
3
DATABASE_URL=psql://urser:un-githubbedpassword@127.0.0.1:8458/database
4
SQLITE_URL=sqlite:///my-local-sqlite.db
5
CACHE_URL=memcache://127.0.0.1:11211,127.0.0.1:11212,127.0.0.1:11213
6
REDIS_URL=rediscache://127.0.0.1:6379/1?client_class=django_redis.client.DefaultClient&password=ungithubbed-secret
7
Advertisement
Answer
if your .env
file is in root project directory so you don’t have to put this
JavaScript
1
4
1
environ.Env.read_env(
2
env_file = os.path.join(BASE_DIR, '.env')
3
)
4
just write this only environ.Env.read_env()
, it will work