简体   繁体   中英

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

在此处输入图片说明

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM