Milano
Milano

Reputation: 18735

Django (Gunicorn) doesn't see ENV VARS in production but Django-shell does

I'm pretty desperate here. I can't figure out why Django doesn't see environment variables even if shell can.

in settings.py

BASE_URL = os.getenv('VUE_APP_WEB_URL','http://127.0.0.1:8080/')

in admin.py

class _UserAdmin...
    ...
    list_display = ('username', 'email', 'is_staff', '_set_pwd_url','base_url')
    list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')

    def base_url(self, obj: User):
        return settings.BASE_URL

in /etc/environment

VUE_APP_WEB_URL=http://my.url.xyz/

Server has been rebooted multiple times, also Gunicorn has been restarted by sudo service gunicorn restart

enter image description here

It's still showing the default value, not the ENV VAR.

Now, when I test it in django shell:

Python 3.8.10 (default, Sep 28 2021, 16:10:42) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> settings.BASE_URL
'http://my.url.xyz/'
>>> 

What is going on?

PS: Browser cache is not the problem.

Upvotes: 0

Views: 1445

Answers (1)

Cl0ud-l3ss
Cl0ud-l3ss

Reputation: 185

Make a .env file in your (preferably root) directory and then configure your gunicorn.service configuration to point to that file.

make a .env file

VUE_APP_WEB_URL= 'http://my.url.xyz/'
ANOTHER_VARIABLE = 'something'

then add EnvironmentFile to your configuration

...

[Service]  
...
EnvironmentFile=/path/to/your/.env
ExecStart=
...            

You can also use pip install django-dotenv which will also look for .env and initialise it.

Upvotes: 2

Related Questions