[Python] How to import environment variables to Django from local file

Discussão em 'Python' iniciado por Stack, Agosto 3, 2025.

  1. Stack

    Stack Membro Participativo

    I'm preparing for production on my first professional Django project, and I'm having issues with environment variables to secure the the application. So far I've managed to create a local file to store all variables on my pc...

    env_variables.py

    import os

    db_user = os.environ.get('db_user')
    db_password = os.environ.get('db_password')

    # AWS DJANGO
    export AWS_ACCESS_KEY_ID = "access_key"
    export AWS_SECRET_ACCESS_KEY = "secret_key"
    export AWS_STORAGE_BUCKET_NAME = "bucket_name"

    print(db_user)
    print(db_password)


    I've used the environment settings(windows) to create username and password. When I run the file they work. I'm using my AWS credentials to test this. I've been under the impression that Django can access this information no matter where it is on my local pc. Correct me if I'm wrong.

    settings.py

    ...

    AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
    AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
    AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')

    ...


    I know that Django isn't accessing this file because I get 400 for all of my media files, but it works when I place the keys directly into the settings.py file. I believe I'm missing a few steps here. I've seen other python coders capable of doing this without having to use something like django-environ or other packages. If anyone can help it would be greatly appreciated because I'd like to do this for all of my projects.

    Edit My Procfile's gunicorn is web: gunicorn project_name.wsgi I have not modified my wsgi file.

    Continue reading...

Compartilhe esta Página