Get absolute static file url in my django template

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

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 to dev:

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

in production

 <link rel="stylesheet" href="https://mycompany.com/static/css/bootstrap.min.css"> 
+7
django django-templates
source share
1 answer

There are two options:

  • recommended: use site frames to display the corresponding domain
  • not recommended: save the current domain as a Django parameter in the settings file, which you use depending on your environment.

Usually I use (1), the only drawback is that you have to update the current domain in the database, but usually this happens only once for deployment.

Then the corresponding domain will be displayed irrelevant where the code works; you should always use the static tag in your template, and not handle the domain mapping manually.

+4
source share

All Articles