Add dynamic data to template
I need to put data into the sidebar. Haven't figured out any other sollution than context_processors. Is this the cleanest and optimal way to do this?
Any help appreciated. I find it a bit strange that it has been so hard to find information re. this issue. So maybe this could be of help to others as well.
# animals/context_processors.py
from animals.models import Cows, Horses
from django.shortcuts import render
def allcows(request):
cows = Cows.objects.all()
return {"cows": cows}
def lasthorses(request):
horses = Horses.objects.all().order_by("-id")[:2]
return {"horses": horses}
Sidebar.html
<h1>Sidebar</h1>
<h3>All cows:</h3>
{%for cow in cows%}
<div>
The name is {{ cow.name }}, and the age of {{ cow.name}} is {{ cow.age }}.
</div>
{%endfor%}
<h3>last 2 horses:</h3>
{%for horse in horses%}
<div>
The name is {{ horse.name }}, and the age of {{ horse.name}} is {{ horse.age }}.
</div>
{%endfor%}
base.html
<body>
<div class="holy-grail-grid">
<header class="header">{% include 'animals/nav.html' %}
</header>
<main class="main-content">
<header id="main-header">
<h1>{% block main_heading %}Main Heading{% endblock %}</h1>
<h3> {% block header_content %}Heading{% endblock %}</h3>
</header>
{% block content %}
{% endblock %}
</main>
<section class="left-sidebar">
<p>My left sidebar{% include 'animals/sidebar.html' %}
</p>
</section>
<aside class="right-sidebar">
<p>My right sidebar{% include 'animals/justinfo.html' %}</p>
</aside>
<footer class="footer">
<p>The footer</p>
</footer>
</div>
</body>
If you always need cows
and horses
, you can just use:
# animals/context_processors.py
from animals.models import Cows, Horses
from django.shortcuts import render
def all_animals(request):
cows = Cows.objects.all()
horses = Horses.objects.order_by('-id')[:2]
return {'cows': cows, 'horses': horses}
and since QuerySet
s are lazy, this will not make any queries if you don't need cows
or horses
in the templates you are rendering.
Note: Normally a Django model is given a singular name [django-antipatterns], so
Cow
instead of.Cows