admin管理员组

文章数量:1394056

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

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

Share asked Sep 30, 2019 at 11:38 cainamcainam 751 silver badge6 bronze badges 2
  • That's impossible. Javascript/jquery is running on the frontend, i.e. in the browser of your users. The .env you're talking about is on the server running Django. What exactly are you trying to achieve? – dirkgroten Commented Sep 30, 2019 at 11:43
  • @dirkgroten I want to store the hostname in the .env file. I use jquery to hit API from the django rest framework. The problem is when running in local I use "localhost" and when I deploy the code it needs to use different url/host. – cainam Commented Sep 30, 2019 at 11:48
Add a ment  | 

1 Answer 1

Reset to default 5

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.

本文标签: javascriptHow to access env file in jqueryStack Overflow