I have an issue getting python-decouple to work in my Django project.
My .env file located in what BASE_DIR in settings.py resolves to:
SECRET_KEY=ARANDOMSECRETKEY
My settings.py:
from pathlib import Path
import locale
from decouple import config
# config.encoding = locale.getpreferredencoding(False)
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
If I start my django project with the config.encoding line commented out, it errors out with:
File "<frozen codecs>", line 322, in decode
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
If I start my project with that line, different error:
Lib\site-packages\decouple.py", line 92, in get
raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option))
decouple.UndefinedValueError: SECRET_KEY not found. Declare it as envvar or define a default value.
I've added the .env file in pretty much every path available now, no luck :( I've also tried to work with a settings.ini file instead:
[settings]
SECRET_KEY=ARANDOMSECRETKEY
This errors out with:
configparser.MissingSectionHeaderError: File contains no section headers.
file: 'xxxx\\settings.ini', line: 1
'ÿþ[\x00s\x00e\x00t\x00t\x00i\x00n\x00g\x00s\x00]\x00\n'
While if I rename the settings.ini file into settings.old, error changes into SECRET_KEY not found. In other words, python-decouple can find the .env and settings.ini files but cannot read them for some reason. Please help :-)
I've also tried creating a fresh venv with just django installed + python-decouple -> same issues. I feel I am missing something very obvious .. but what?
To anyone struggling with the same issue, the answer is weird encoding of the .env file. I created this file in powershell (echo . > .env) which set encoding to something weird. Set encoding to UTF-8 or simply create the file in your editor instead, should fix the above.