[Django]-Cannot pass variables to django home template from another template in app

2👍

✅

It seems that when you are using

url(r'^$', TemplateView.as_view(template_name='pages/home.html') ,  name="home")

You are not defining posts at all. To make it working you have to pass context with posts to this name="home" view but you are using default as_view which doesn’t pass posts.

I would make it like so:

news/urls.py:

url(r'^$', views.home,  name="home")

news/views.py:

from news.models import News
from django.shortcuts import render
from django.template import RequestContext

def home(request):
   posts = News.objects.all()
   return render(request, 'home.html', {'posts':posts })

news/templates/news.html:

{% load i18n %} 
{% block inner_content %}
<h2>News</h2>
    :D
    {% for post in posts %}
    {{ post.title }}
    {{ post.body }}
    {% endfor %}
{% endblock inner_content %}

templates/home.html:

{% extends "base.html" %}
{% load i18n %}
{% block content %}
<section id="portfolio">
    <div class="container">

  {% include "news.html" with posts=posts %}

    </div>
</section>
{% include "footer.html" %}
{% endblock content %}

Leave a comment