1

Possibly I'm misunderstanding the inheritance of templates in Django, but why doesn't the below code work? Both child templates are inheriting from the parent template with different block names.

base.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>test</h1>

{% block index %}{% endblock %}
{% block nav %}{% endblock %}
</body>
</html>

index.html

{% extends 'blog/base.html' %}
{% block index %}
<h1>This is the index.html page</h1>
{% endblock %}

nav.html

{% extends 'blog/base.html' %}
{% block nav %}
<h1>This is the nav.html</h1>
{% endblock %}

I am accessing this template by: urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls'))
]

blog/urls.py:

urlpatterns = [
    path('', views.home, name='home'),
    path('nav/', views.home, name='nav')
]

blog/views.py

def home(request):
    return render(request, 'blog/index.html')

Using the URL of:

localhost:8000/blog

HTML Output:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>test</h1>


<h1>This is the index.html page</h1>


</body>
</html>

I'm trying to grasp the concept of using multiple blocks so that I can place them on the templates that I need.

Jason G
  • 170
  • 1
  • 2
  • 13

1 Answers1

3

You can not render two views in one HTTP request. To include content from a different template, simply use include for the nav.html if its is not going to be called independently.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>test</h1>
{% include 'nav.html' %}
{% block index %}{% endblock %}
</body>
</html>
MohitC
  • 4,541
  • 2
  • 34
  • 55