Django: The static tag not loading on extended html when linking an image but works for CSS style sheet?

52 views Asked by At

I have a layout.html file as follows:

{% load static %}
<!DOCTYPE html>
<html lang="en">
    <head>
        <link href="{% static 'app/styles.css' %}" rel="stylesheet">
    </head>
    <body>
        {% block body %}
        {% endblock %}
    </body>
</html>

and a extended.html as follows:

{% extends "layout.html" %}

{% block body %}
    <div class="maincontainer">
        <h1>Extended</h1>
        <img src="{% static 'app/images/image.svg' %}" alt="image">
    </div>
{% endblock %}

When I load the exnteded.html I get the follwoing error:

django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 13: 'static', expected 'empty' or 'endfor'. Did you forget to register or load this tag?

I have tested a few scenarios out:

  1. If I remove the <img src="{% static 'app/images/image.svg' %}" alt="image"> from the extended.html the CSS style sheet loads perfectly.
  2. If I add {% load static %} to the extended.html the image and CSS style sheet both load.

I have had a look at the Django docs and have ensured that the settings.py file does have django.contrib.staticfiles in INSTALLED_APPS and STATIC_URL = "static/".

Am I missing something here?

1

There are 1 answers

0
Harsh2308 On

You don't define app name in load static.

You have just try to remove app name in your load static, Like,

Your code:

<link href="{% static 'app/styles.css' %}" rel="stylesheet">

Try My Answer:

<link href="{% static 'styles.css' %}" rel="stylesheet">

And also remove app name in load images,

Your code:

<img src="{% static 'app/images/image.svg' %}" alt="image">

Try My Answer:

<img src="{% static '/images/image.svg' %}" alt="image">