How to add environment variables to command line in Django runserver

Viewed 1295

I would appreciate it if you could help me.

I want to add some environment variables to command line as following:

python manage.py runserver myvar=myvar_value

I use the myvar in views.py request function, In fact the servers do different works I want to make a flag with myvar to determine if the myvar is equal 1, runs some functions in views file and if myvar is 0, runs some other function.

1 Answers

The nicest and most Django way is to use the settings.py file for this.

# settings.py
import os

MY_VAR = os.environ.get("MYVAR", default="default")
# views.py
from django.conf import settings

def my_view(request):
    my_var = settings.MY_VAR
    # do something with it

You can then start the server this way:

$ MYVAR=foobar python manage.py runserver

This is a standard POSIX way to add env vars to called programs. If you then deploy it via Docker you could use a .env file.

Related