So I have django project with jquery for interactivity in frontend. I already have .env file to store database configuration to be used by django settings.py, but I need jquery to be able to access the .env file too.
From what I read in dotenv documentation, I need to install the dotenv using npm or yarn. But I think jquery don't have/use npm? I am a newbie in javascript
Your script can't have access to .env, since it's running in your users' browsers.
First, if your API is hosted on the same domain as your page itself, you don't need to specify a hostname, just use relative URLs ('/api/v1/path/to/resource/'). That way your script doesn't need to know the host. Also, in Javascript, document.location
will give you all the information about the current host.
Second, if it's not the same or you want other URL parameters to be set by Django for your script to use, set a variable in your template using a context variable. E.g. if your view fetches settings.API_URL
and passes it as api_url
to the context, you can do this in your template:
<script>var APIUrl = "{{ api_url }}"</script>
Then, as long as your jQuery script runs after this variable was defined, it will have access to it.