[Django]-Django template tags forloop

3👍

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

Leave a comment