[Answered ]-Content using {% include %} not appearing on detailed page Django

1πŸ‘

βœ…

The get_context_data method belongs in your view. If you move it there, your sidebar should work.

However, there is a much cleaner way to achieve this by using a context processor. Context processors allow you to make certain data available to all of your templates, no matter where they are.

Create context_processors.py in your project module directory, and make it look something like this:

# myproject/myproject/context_processors.py

from myapp.models import FullArticle


def sidebar_articles(request):
    """Return the 5 most recent articles for the sidebar."""
    articles = FullArticle.objects.all()[:5]
    return {'SIDEBAR_ARTICLES': articles}

You will have to enable the context processor in your settings.py. Do this by adding the TEMPLATE_CONTEXT_PROCESSORS default setting, and appending your new context processor to the bottom. Like this:

# settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
  "django.contrib.auth.context_processors.auth",
  "django.core.context_processors.debug",
  "django.core.context_processors.i18n",
  "django.core.context_processors.media",
  "django.core.context_processors.static",
  "django.core.context_processors.tz",
  "django.contrib.messages.context_processors.messages",
  "myproject.context_processors.sidebar_articles",
)

Now you will be able to reference SIDEBAR_ARTICLES from any of your templates. Your sidebar.html could be rewritten as:

<!-- myapp/templates/detailed.html -->

<div>
  {% for article in SIDEBAR_ARTICLES %}
  <h1>{{ article.title }}</h1>
  and so on ...
  {% endfor %}
</div>
πŸ‘€dustinfarris

1πŸ‘

I believe it is necessary to pass the right arguments to your included template. See https://docs.djangoproject.com/en/dev/ref/templates/builtins/#include for more documentation.

Template will probally look like: {% include "sidebar.html" with article=object %}

Update 1
After reading the docs about detailview, my following suggestions
(https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-display/#detailview) It appears your context only contains a object. So we have to pass this to this included slider template.

{% include "slider.html" with article=object %}

The problem within your sidebar template is that you don’t have an object_list within your context. You can add this to your DetailView as shown in the example. So the method would look like.

def get_context_data(self, **kwargs):
    context = super(BlogDetail, self).get_context_data(**kwargs)
    context['object_list'] = models.FullArticle.objects.published()
    return context

And the include of the template should look like.

{% include "sidebar.html" with object_list=object_list %}
πŸ‘€Blackeagle52

0πŸ‘

Take care you are passing correctly your context to template. But probably you have to add spaces between β€˜{{β€˜ bracket and variable name. Ex. {{ article.title }}

Leave a comment