Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Get absolute url for static files

Tags:

In Django, when I use:

{{ request.build_absolute_uri }}{% static "img/myimage.jpg" %} 

It produces: 'http://myurl.com//static/img/myimage.jpg'. This produces an error.

How can I remove the double slashes?

The STATIC URL is:

STATIC_URL = '/static/' 

But I don't think removing the first '/' would be a good idea.

like image 346
cusejuice Avatar asked May 19 '14 20:05

cusejuice


People also ask

How do I get an absolute URL in Django?

To get the full or absolute URL (with domain) in Python Django, we can use the build_absolute_uri method. to call request. build_absolute_uri with reverse('view_name', args=(obj.pk, ) to get the path of the view with reverse . Then we call “request.

Does Django serve static files?

Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as “static files”. Django provides django.

How do I run Collectstatic in Django?

Using the collectstatic command, Django looks for all static files in your apps and collects them wherever you told it to, i.e. the STATIC_ROOT . In our case, we are telling Django that when we run python manage.py collectstatic , gather all static files into a folder called staticfiles in our project root directory.


1 Answers

The build_absolute_uri method builds an absolute uri for the current page. That means that if you're on e.g. 'http://myurl.com/login/', the resulted full url would be 'http://myurl.com/login//static/img/myimage.jpg'.

Instead, use request.get_host() (optionally together with request.scheme for the url scheme), or preferably, use the sites framework to set a template variable to the current site domain. The get_host() method has some issues regarding proxies.

The get_host() method will return the current domain without a path appended.

like image 142
knbk Avatar answered Sep 22 '22 12:09

knbk