3

I am studying Django. In my settings.py :

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

and when I try to add an image in a template,

<img src="{% static "img/person.png" %}"/>

<img src="{{ STATIC_URL }}img/person.png" />

<img src="/static/img/person.png" />

All three are shown in the browser as:

<img src="/static/img/person.png" />

Then, What is the different between them?

If there is no problem, can I use

<img src="/static/img/person.png" /> 

in the template code?

BingbongKim
  • 549
  • 1
  • 6
  • 18
  • 1
    With first approach you can change `STATIC_URL` in single place and everything will be working. With hardcoded URLs you'll have to go through whole codebase and change (potentially) hundreds of URLs manually. You can also customize `STATIC_URL` depending on environment. For example for loading static files from CDN in production. – Yaroslav Admin Sep 19 '17 at 16:59

1 Answers1

4

The problem with hardcoded URLs <img src="/static/img/person.png" /> is that if in future you want to change static URL you have to go through all files to replace it with newer one, and usually in production sometimes we want to use CDN to serve static content and that is not served via /static/.

For the other difference between {% static %} and {{ STATIC_URL }} check this answer.

Aamir Rind
  • 38,793
  • 23
  • 126
  • 164