Django-environ error

Hello there I got this error
raise ImproperlyConfigured(error_msg) from exc
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable

I have the .env file in same directory as setting.py

and here are the code in setting.py

import os
from pathlib import Path
import environ

Create an instance of the Env class

Build paths inside the project like this: BASE_DIR / ‘subdir’.

BASE_DIR = Path(file).resolve().parent.parent

Read the .env file and set the environment variables

environ.Env.read_env(BASE_DIR / ‘.env’)

env = environ.Env( # ← Updated!
# set casting, default value
DEBUG=(bool, False),
)

Quick-start development settings - unsuitable for production

See Deployment checklist | Django documentation | Django

SECURITY WARNING: keep the secret key used in production secret!

SECRET_KEY = env(‘SECRET_KEY’)

any help please

Django docs say:

The ImproperlyConfigured exception is raised when Django is somehow improperly configured – for example, if a value in settings.py is incorrect or unparseable.

If I had this issue, I would probably do this:

  • check if I have a SECRET_KEY variable in the .env file:
    SECRET_KEY=abck$y+7+vhh+s_3&wj1blfycq+9i*32&2i^@*x4t3!jmf)+re

  • check if I have a SECRET_KEY set in settings.py:
    SECRET_KEY = env(‘SECRET_KEY’)

  • check for typos

Hey there!
When posting code here, surround with the code tag, available on the editor, or surround the code with 3 backtick ` characters.

Maybe try setting the overwrite parameter to True on the read_env call.
If that doesn’t work you can check if the .env is in fact being found.

env_file_path = BASE_DIR / '.env'
if not env_file_path.exists():
  raise ValueError(f"{env_file_path=} does not exists")

This will help you figure it out if the BASE_DIR actually is the directory that you’re expecting.
(Probably it’s not, because you’re creating the BASE_DIR based on __file__, the settings file, but are going up into the parent directories.

Thank you all, it work