How can I give a value to a Django environment variable from within the application itself?

1.1k Views Asked by At

I developed an application with its respective access login, when the user tries to log in, he must select a value that will be used throughout the execution of the application until the user closes the session. I have my project configured with environment variables, I use the django-environ 0.8.1 library to configure these variables so that my application can access them in the .env file. How can I manage the login variable with these environment variables?

import environ

# environ init
env = environ.Env()
environ.Env.read_env()

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool('DEBUG', default = False)

# This is the variable that I need to change according to the option 
# that the user chooses when logging in
DATABASE_SAP_CHOSEN = 'SBOJOZF'
1

There are 1 best solutions below

2
Thomas Lewin On

It seems like you want to use sessions.

My application requires the user select a client from a form selection once logged in, as each page is used to view/manipulate the clients data.

Example:

def post(self, request):
        if request.method == 'POST':
            request.session['client_id'] = client.objects.get(pk=request.POST['client_id'])
        return redirect(self.request.path)

Then when I want to call it in another view:

def get(self, request):
        selected_client = request.session.get('client_id')
        if selected_client == None:
           redirct(reverzelazy('client_selector'))