Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template tags forloop

Tags:

python

django

I have created a template tag and trying to loop through the results from the template tag but I don't get any results

tags.py

from django import template
from loadprograms import dbcontext

register = template.Library()


    @register.simple_tag
    def get_category():
        x = dbcontext.DBContext()
        results = x.executequery("Select name from Categories")
        categories = [each[0] for each in results]
        return categories 

template code

{% load category_tags %}
{% get_category %}
{% for each in get_category %}
    {{ each }}
{% endfor %}

The {% get_category %} prints all the categories without any issues but the for loop stmt that loop through the results does not work

What could be the problem?

like image 387
user1050619 Avatar asked Dec 04 '25 15:12

user1050619


1 Answers

To make this change in your tag, you'll have to set a variable in the context, but if your objective is to have a list of categories available in templates, just like you would have passed it in from the view - then you need to write a template context processor, which will allow all views to have this variable in their context.

A template context processor is just a method that adds to the request context, by returning a dictionary. Think of it like a view function, that just returns a context.

from .models import Categories

def cat_names(request):
    return {'category_names': Category.objects.values_list('name', flat=True)}

To activate this context processor, you have to do a few things:

  1. Add the above code to a file called template_processors.py in the same place as your models.py and views.py.

  2. In your settings.py, add the fully-qualified name of the method to the TEMPLATE_CONTEXT_PROCESSORS setting, making sure you don't override the defaults. To do this easily, import the default settings first, then add to it:

    from django.conf.default_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
    
    TEMPLATE_CONTEXT_PROCESSORS = TCP + ('yourapp.template_processors.cat_names',)
    
  3. Use the render shortcut, which will make sure the context is correctly passed.

In your views, you can now just do this:

from django.shortcuts import render

def home(request):
   return render(request, 'home.html')

In your home.html, you can now do:

{% for name in category_names %}
   {{ name }}
{% endfor %}
like image 64
Burhan Khalid Avatar answered Dec 07 '25 03:12

Burhan Khalid