Добавьте динамические данные в шаблон

Мне нужно поместить данные в боковую панель. Не нашел другого решения, кроме context_processors. Это самый чистый и оптимальный способ сделать это?

Любая помощь приветствуется. Мне кажется немного странным, что было так трудно найти информацию по этому вопросу. Так что, возможно, это поможет и другим.

# 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>

Если вам всегда нужны cows и horses, вы можете просто использовать:

# 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}

и поскольку QuerySet ленивы, это не вызовет никаких запросов, если вам не нужны cows или horses в шаблонах, которые вы рендерите.


Note: Normally a Django model is given a singular name [django-antipatterns], so Cow instead of Cows.

Вернуться на верх