Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I do render a queryset in a Django base template?

I have a base template which extends to almost every other templates in my project. I am trying to populate my categories navigation bar with some queryset from my database but am failing with my approach. Since the base template has no url, I am finding it difficult to render. This is what I've tried:

this is my views function

def base(request):
    categories = list(Category.objects.all())
    context = {
        'categories': categories
    }
    return render(request, 'ads/base.html', context)

this is my html

{% for category in categories %}
    <div class="nav-item dropdown">
        <a href="#" class="nav-link dropdown-toggle" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            { category.name }}&nbsp;
            <span class="float-right text-muted">
                <small>
                    <i class="fas fa-chevron-down"></i>
                </small>
            </span>
        </a>
    </div>
{% endfor %}

I just want to populate my navbar with the categories queryset

like image 845
cy23 Avatar asked Nov 15 '25 18:11

cy23


1 Answers

Even if the base view had a URL, that would not make any difference. A URL triggers a view, and that view renders a response. A template has not (much) to do with it. A template is sometimes used as a way to generate such response. But it can only render with data that is passed somehow. For example through that view, or through template tags, context processors, etc.

We can for example define a context processor. In your app, you can define a function in the context_processors.py file:

# app/context_processors.py

def categories(request):
    from app.models import Category
    return {'categories': Category.objects.all()}

In the settings.py you can then add the function to the context processors:

# settings.py

# ...

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'app.context_processors.categories'
            ],
        },
    },
]

Now each time you render a template, you will add a categories variable to the context that is mapped on the Category.objects.all() queryset. QuerySets are evaluated lazily, so in case you do not need to iterate over it, the query is not performed on the database.

like image 199
Willem Van Onsem Avatar answered Nov 17 '25 09:11

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!