djangowagtaildjango-settingsdjango-environ

Why am I getting a NoneType for Allowed Host in Django-Environ when I set allowed host?


The settings code is

import os
import environ

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


env = environ.Env(DEBUG=(bool, False))

environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

the allowed host is written as

ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS").split(',')

the .env file has ALLOWED_HOSTS as

ALLOWED_HOSTS=localhost 127.0.0.1 [::1]

why am I getting the fail code

AttributeError: 'NoneType' object has no attribute 'split'

when I run the command

docker-compose up --build -d --remove-orphans

Solution

  • You are doing it in the wrong way -

    1. the env value should be comma-separated
      # env file
      
      ALLOWED_HOSTS=localhost,127.0.0.1,[::1]
      
    2. Access the env variable using env (instance of Env(...))
      # settings.py
      
      env = environ.Env(DEBUG=(bool, False))
      
      environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
      ALLOWED_HOSTS = env.list('ALLOWED_HOSTS')
      # or
      # ALLOWED_HOSTS = env('ALLOWED_HOSTS', cast=list)