Home > Software design >  header not visible in django page
header not visible in django page

Time:07-31

I am trying to render a page with header but header is not being rendered. content of categories.html is displaying perfectly. I have added header block on index.html page.What am i doing wrong here?

index.html

    {% load static %}

    <link rel="icon" href="{% static 'stocks/logo.png' %}">
    <html>
    <body>
        <div>
            {% block header %}
            {% endblock %}
        </div>

        {% block stocks_page %}
        {% endblock %}
    </div>
    </body>

    </html>

header.html

    {% extends "stocks/index.html" %}

    {% block header %}

    <h1>Header content goes here</h1>

    {% endblock %}

categories.html

    {% extends "stocks/index.html" %}

    {% load static %}
    {% block stocks_page %}
    <link rel="stylesheet" type="text/css" href="{% static 'stocks/style.css' %}">

    {% if categories %}
    <h2>Product categories</h2>
    <table>
        <tr>
            <th>Name</th>
            <th>Count</th>
        </tr>
        {% for each in categories %} 
            <tr>
                <td>{{ each.name }}</td>
                <td>{{ each.count }}</td>
            </tr>
        {% endfor %}
    </table>
    {% endif %}
    <form action="/stocks/" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit">
    </form>
    {% endblock %}

views.py

    def product_categories(request):
            ----------------------
            < code >
            ----------------------
            return render(request, 'stocks/categories.html')

CodePudding user response:

You will need to write code inside the block quotes if you want to use the header. For example, in your categories.html file,

{% extends "stocks/index.html" %}

{% load static %}

{% block header %} <---- You would need to use block every time you render

<h1>Header content goes here</h1>

{% endblock %}

{% block stocks_page %}
<---- stock_page_content ---->
{% endblock %}

To make things simpler, if you want to include header in every page that extend from index.html, use this. In your index.html file:

{% load static %}

<link rel="icon" href="{% static 'stocks/logo.png' %}">
<html>
<body>
    <div>
        {% include 'header.html' %} <--- include replaces the file in render
    </div>

    {% block stocks_page %}
    {% endblock %}
</div>
</body>

</html>

More information: https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#include

CodePudding user response:

{% include 'header.html' %}

try this in your index.html

this may fix your problem

  • Related