4

I am doing the django tutorial on realpython https://realpython.com/get-started-with-django-1/ In one of the templates they add {% load static %} to load the static files for an app. In the same template they also load an image like this <img class="card-img-top" src="{% static project.image %}">. The static keyword here tells django to look for the filename defined in project.image in the static folder. When i remove {% load static %} the image is still displayed. So why would i need this part if the image can be perfectly rendered without it? Heres the code:

    {% extends "base.html" %}
<!--{% load static %}-->

{% block page_content %}
<h1>Projects</h1>
<div class="row">
    {% for project in projects %}
    <div class="col-md-4">
        <div class="card mb-2">
            <img class="card-img-top" src="{% static project.image %}">
            <div class="card-body">
                <h5 class="card-title">{{ project.title }}</h5>
                <p class="card-text">{{ project.description }}</p>
                <a href="{% url 'project_detail' project.pk %}" class="btn btn-primary">Read more</a>
            </div>
        </div>
    </div>
    {% endfor %}
</div>
{% endblock %}
FAM_Maurice
  • 363
  • 3
  • 10
  • 3
    By wrapping it in you're not actually removing the `{% load %}` instruction. Delete the line and you should get an error telling you that the template tag `{% static %}` is not defined. `{% load static %}` tells django to load a set of template tags/filters defined in the file `static.py` (in a folder `templatetags` in any of the apps of your project). The same way you can define your own tags, put them in a file `util_tags.py` and load them with `{% load util_tags %}`. – dirkgroten Dec 12 '19 at 15:58

1 Answers1

6

You are using HTML comment which is not processed by Django rather it ignores that and executes the template tag. Try using template comment {# you long comment #}.

So the code changes to

   {% extends "base.html" %}
{# {% load static %} #}

{% block page_content %}
<h1>Projects</h1>
<div class="row">
    {% for project in projects %}
    <div class="col-md-4">
        <div class="card mb-2">
            <img class="card-img-top" src="{% static project.image %}">
            <div class="card-body">
                <h5 class="card-title">{{ project.title }}</h5>
                <p class="card-text">{{ project.description }}</p>
                <a href="{% url 'project_detail' project.pk %}" class="btn btn-primary">Read more</a>
            </div>
        </div>
    </div>
    {% endfor %}
</div>
{% endblock %}

{% load static %} actually loads the tag static. This tag allows you to embed links for static files https://docs.djangoproject.com/en/3.0/howto/static-files/#configuring-static-files.

You can also create your custom tag read https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/

Faisal Manzer
  • 2,089
  • 3
  • 14
  • 34