在我的Django模板中获取绝对静态文件URL

时间:2022-09-04 12:33:56

I want to know how can I get the absolute URL of my static file directly in my template in Django ?

我想知道如何直接在Django的模板中获取静态文件的绝对URL?

For now in my template :

现在在我的模板中:

<link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}">

return

返回

<link rel="stylesheet" href="/static/css/bootstrap.min.css">

How can I get on dev:

我如何进入开发:

<link rel="stylesheet" href="http://127.0.0.1:8000/static/css/bootstrap.min.css">

on production

在生产上

<link rel="stylesheet" href="https://mycompany.com/static/css/bootstrap.min.css">

1 个解决方案

#1


4  

There are two options:

有两种选择:

  1. recommended: use the sites framework to render the appropriate domain
  2. 建议:使用sites框架呈现适当的域
  3. not recommended: store your current domain as a Django setting in the settings file you use depending on your environment
  4. 不推荐:根据您的环境,将当前域存储为您使用的设置文件中的Django设置

I usually go for (1), the only downside being that you have to update the current domain in the DB, but that usually happens just once per deployment.

我通常会选择(1),唯一的缺点是你必须更新数据库中的当前域,但每次部署通常只发生一次。

Then the appropriate domain will be displayed irrelevant of where code is running; you should always use the static tag in your template, rather than handling the display of the domain manually.

然后显示相应的域与代码运行的位置无关;您应始终在模板中使用静态标记,而不是手动处理域的显示。

#1


4  

There are two options:

有两种选择:

  1. recommended: use the sites framework to render the appropriate domain
  2. 建议:使用sites框架呈现适当的域
  3. not recommended: store your current domain as a Django setting in the settings file you use depending on your environment
  4. 不推荐:根据您的环境,将当前域存储为您使用的设置文件中的Django设置

I usually go for (1), the only downside being that you have to update the current domain in the DB, but that usually happens just once per deployment.

我通常会选择(1),唯一的缺点是你必须更新数据库中的当前域,但每次部署通常只发生一次。

Then the appropriate domain will be displayed irrelevant of where code is running; you should always use the static tag in your template, rather than handling the display of the domain manually.

然后显示相应的域与代码运行的位置无关;您应始终在模板中使用静态标记,而不是手动处理域的显示。