The SECRET_KEY setting must not be empty || Available at Settings.py

2024/10/14 15:27:33

I tried to find this bug, but don't know how to solve it.

I kept getting error message "The SECRET_KEY setting must not be empty." when executing populate_rango.py

I have checked on settings.py and the secret key is already inserted.

Here is the full error message:

E:\PythonCode\django1\tango_with_django>python populate_rango.py
Starting Rango population script...
Traceback (most recent call last):File "populate_rango.py", line 27, in <module>from rango.models import Category, PageFile "E:\PythonCode\django1\tango_with_django\rango\models.py", line 1, in <mo
dule>from django.db import modelsFile "C:\python27\lib\site-packages\django\db\models\__init__.py", line 5, in
<module>from django.db.models.query import QFile "C:\python27\lib\site-packages\django\db\models\query.py", line 17, in <m
odule>from django.db.models.deletion import CollectorFile "C:\python27\lib\site-packages\django\db\models\deletion.py", line 4, in
<module>from django.db.models import signals, sqlFile "C:\python27\lib\site-packages\django\db\models\sql\__init__.py", line 4,in <module>from django.db.models.sql.subqueries import *File "C:\python27\lib\site-packages\django\db\models\sql\subqueries.py", line
12, in <module>from django.db.models.sql.query import QueryFile "C:\python27\lib\site-packages\django\db\models\sql\query.py", line 22, i
n <module>from django.db.models.sql import aggregates as base_aggregates_moduleFile "C:\python27\lib\site-packages\django\db\models\sql\aggregates.py", line
9, in <module>ordinal_aggregate_field = IntegerField()File "C:\python27\lib\site-packages\django\db\models\fields\__init__.py", line116, in __init__self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACEFile "C:\python27\lib\site-packages\django\conf\__init__.py", line 54, in __ge
tattr__self._setup(name)File "C:\python27\lib\site-packages\django\conf\__init__.py", line 49, in _set
upself._wrapped = Settings(settings_module)File "C:\python27\lib\site-packages\django\conf\__init__.py", line 151, in __i
nit__raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be
empty.E:\PythonCode\django1\tango_with_django>python populate_rango.py
Starting Rango population script...
Traceback (most recent call last):File "populate_rango.py", line 27, in <module>from rango.models import Category, PageFile "E:\PythonCode\django1\tango_with_django\rango\models.py", line 1, in <mo
dule>from django.db import modelsFile "C:\python27\lib\site-packages\django\db\models\__init__.py", line 5, in
<module>from django.db.models.query import QFile "C:\python27\lib\site-packages\django\db\models\query.py", line 17, in <m
odule>from django.db.models.deletion import CollectorFile "C:\python27\lib\site-packages\django\db\models\deletion.py", line 4, in
<module>from django.db.models import signals, sqlFile "C:\python27\lib\site-packages\django\db\models\sql\__init__.py", line 4,in <module>from django.db.models.sql.subqueries import *File "C:\python27\lib\site-packages\django\db\models\sql\subqueries.py", line
12, in <module>from django.db.models.sql.query import QueryFile "C:\python27\lib\site-packages\django\db\models\sql\query.py", line 22, i
n <module>from django.db.models.sql import aggregates as base_aggregates_moduleFile "C:\python27\lib\site-packages\django\db\models\sql\aggregates.py", line
9, in <module>ordinal_aggregate_field = IntegerField()File "C:\python27\lib\site-packages\django\db\models\fields\__init__.py", line116, in __init__self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACEFile "C:\python27\lib\site-packages\django\conf\__init__.py", line 54, in __ge
tattr__self._setup(name)File "C:\python27\lib\site-packages\django\conf\__init__.py", line 49, in _set
upself._wrapped = Settings(settings_module)File "C:\python27\lib\site-packages\django\conf\__init__.py", line 151, in __i
nit__raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be
empty.

Here is settings.py:

"""
Django settings for tango_with_django project.For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')TEMPLATE_DIRS = (TEMPLATE_PATH,)# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y130-j9oz4r5aoamn_n=+s-*7n)*3^s$jmf4(qw6ik28()g^(n'# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = TrueTEMPLATE_DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = ('django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rango',
)MIDDLEWARE_CLASSES = ('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 = 'tango_with_django.urls'WSGI_APPLICATION = 'tango_with_django.wsgi.application'# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databasesDATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3','NAME': os.path.join(BASE_DIR, 'db.sqlite3'),}
}# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/STATIC_URL = '/static/'STATIC_PATH = os.path.join(BASE_DIR, 'static')STATICFILES_DIRS = (STATIC_PATH,
)

Here is the populate_rango.py:

import osdef populate():python_cat = add_cat('Python')add_page(cat=python_cat,title="Official Python Tutorial",url="http://docs.python.org/2/tutorial/")for c in Category.objects.all():for p in Page.objects.filter(category=c):print "- {0} - {1}".format(str(c),str(p))def add_page(cat, title, url, views=0):p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0]return pdef add_cat(name):c = Category.objects.get_or_create(name=name)[0]return c#start execution here
if __name__=='__main__':print "Starting Rango population script..."os.environ.setdefault('DJANGO_SETTINGS_MODULE','tango_with_django')from rango.models import Category, Pagepopulate()
Answer

If you can post your project's directory structure (as mentioned by @knbk), we can help troubleshoot more. Assuming the project name is 'tango_with_django' and most of the setup is local and default, then this modification should fix it:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django.settings')

If you're running 'python manage.py runserver' instead of 'python populate_rango.py', then make sure you have the following code in each of these files:

manage.py

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tango_with_django.settings")

wsgi.py (for server setup)

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tango_with_django.settings")
https://en.xdnf.cn/q/69401.html

Related Q&A

Pandas: Applying Lambda to Multiple Data Frames

Im trying to figure out how to apply a lambda function to multiple dataframes simultaneously, without first merging the data frames together. I am working with large data sets (>60MM records) and I …

scipy.minimize - TypeError: numpy.float64 object is not callable running

Running the scipy.minimize function "I get TypeError: numpy.float64 object is not callable". Specifically during the execution of:.../scipy/optimize/optimize.py", line 292, in function_w…

Flask, not all arguments converted during string formatting

Try to create a register page for my app. I am using Flask framework and MySQL db from pythonanywhere.com. @app.route(/register/, methods=["GET","POST"]) def register_page(): try:f…

No module named objc

Im trying to use cocoa-python with Xcode but it always calls up the error:Traceback (most recent call last):File "main.py", line 10, in <module>import objc ImportError: No module named …

Incompatible types in assignment (expression has type List[nothing], variable has type (...)

Consider the following self-contained example:from typing import List, UnionT_BENCODED_LIST = Union[List[bytes], List[List[bytes]]] ret: T_BENCODED_LIST = []When I test it with mypy, I get the followin…

How to convert XComArg to string values in Airflow 2.x?

Code: from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults from airflow.providers.google.cloud.hooks.gcs import GCSHookclass GCSUploadOperator(BaseOperator):@appl…

Python dryscrape scrape page with cookies

I wanna get some data from site, which requires loggin in. I log in by requestsurl = "http://example.com" response = requests.get(url, {"email":"[email protected]", "…

Python retry using the tenacity module

Im having having difficulty getting the tenacity library to work as expected. The retry in the following test doesnt trigger at all. I would expect a retry every 5 seconds and for the log file to refle…

How to write own logging methods for own logging levels

Hi I would like to extend my logger (taken by logging.getLogger("rrcheck")) with my own methods like: def warnpfx(...):How to do it best? My original wish is to have a root logger writing …

How to use pandas tz_convert to convert to multiple different time zones

I have some data as shown below with hour in UTC. I want to create a new column named local_hour based on time_zone. How can I do that? It seems like pandas tz_convert does not allow a column or panda…