python - Django template tags forloop -
i have created template tag , trying loop through results template tag don't results
tags.py
from django import template loadprograms import dbcontext register = template.library() @register.simple_tag def get_category(): x = dbcontext.dbcontext() results = x.executequery("select name categories") categories = [each[0] each in results] homecoming categories
template code
{% load category_tags %} {% get_category %} {% each in get_category %} {{ each }} {% endfor %}
the {% get_category %} prints categories without issues loop stmt loop through results not work
what problem?
to create alter in tag, you'll have set variable in context, if objective have list of categories available in templates, have passed in view - need write template context processor, allow views have variable in context.
a template context processor method adds request context, returning dictionary. think of view function, returns context.
from .models import categories def cat_names(request): homecoming {'category_names': category.objects.values_list('name', flat=true)}
to activate context processor, have few things:
add above code file called template_processors.py
in same place models.py
, views.py
.
in settings.py
, add together fully-qualified name of method template_context_processors
setting, making sure don't override defaults. easily, import default settings first, add together it:
from django.conf.default_settings import template_context_processors tcp template_context_processors = tcp + ('yourapp.template_processors.cat_names',)
use render
shortcut, create sure context correctly passed.
in views, can this:
from django.shortcuts import render def home(request): homecoming render(request, 'home.html')
in home.html
, can do:
{% name in category_names %} {{ name }} {% endfor %}
python django
No comments:
Post a Comment