I am trying to pass the user objects to my template via a templatetag. I first tried simple_tag but apparently it is only for strings? Anyway this is what I have so far:
templatetags/profiles.py
from django.template import Library, Node, Template, VariableDoesNotExist, TemplateSyntaxError, \
Variable
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import models
class userlist(Node):
def __init__(self, format_string):
self.format_string = format_string
def render(self, context):
try:
users = self.format_string
return users
except VariableDoesNotExist:
return None
def get_profiles(parser, token):
return userlist(User.objects.all())
register = Library()
register.tag('get_profiles', get_profiles)
This is what I have in my template to test it:
{% load profiles %}
{% get_profiles %}
{% for p in get_profiles %} {{ p }} {% endfor %}
I only get [, , , , ] printed out or if I change User.objects.all() to User.objects.count() I get the correct number. The for iteration in my template doesn’t seem to do anything. what is wrong?
What is format string? You need to call the template tag like this:
So you need a template tag like