Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the absolute static file URL in my Django template

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

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">
like image 837
Guillaume Vincent Avatar asked Mar 08 '14 12:03

Guillaume Vincent


People also ask

How do I get an absolute URL in Django?

Use handy request. build_absolute_uri() method on request, pass it the relative url and it'll give you full one. By default, the absolute URL for request. get_full_path() is returned, but you can pass it a relative URL as the first argument to convert it to an absolute URL.

Where are static files Django?

STATICFILES_DIRS: By default, static files are stored at the app-level at <APP_NAME>/static/ . The collectstatic command will look for static files in those directories. You can also tell Django to look for static files in additional locations with STATICFILES_DIRS .

What does {% mean in Django?

{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.


1 Answers

There are two options:

  1. recommended: use the sites framework to render the appropriate domain
  2. not recommended: store your current domain as a Django setting in the settings file you use depending on your environment

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.

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.

like image 88
Joseph Victor Zammit Avatar answered Sep 17 '22 17:09

Joseph Victor Zammit