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">
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.
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 .
{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
There are two options:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With