How to hide google map api key in django before pushing it on github?

Viewed 3003

This is my google address api script which contains the api key

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=api_key&libraries=places&callback=ActivatePlacesSearch">

I have used .env file in project directory to hide sensitive info from settings.py file. How can I use .env file to hide my api key from my template?

1 Answers

Define a variable in your .env file, for example:

GOOGLE_MAPS_API_KEY="your_key"

Then in myproject/settings.py:

GOOGLE_MAPS_API_KEY = os.environ.get('GOOGLE_MAPS_API_KEY')

Then in your views.py file:

from django.conf import settings

def my_view(request):
    context = {
        'api_key': settings.GOOGLE_MAPS_API_KEY
    }
    return render('template.html', context)

then you can access api_key in the template.

Note (thanks to trixn in the comments): Make sure the .env file is included in your .gitignore file so that it doesn't get checked into source control and leak your token. If you've used a standard .gitignore for Python, it should already be included.

Related