Django Templatetag with User objects
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开发者_Python百科 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:
{% get_all_users as allusers %}
{% for user in allusers %}
{{ user.first_name }}
{% endfor %}
So you need a template tag like
class GetAllUsers(Node):
def __init__(self, varname):
# Save the variable that we will assigning the users to
self.varname = varname
def render(self, context):
# Save all the user objects to the variable and return the context to the template
context[self.varname] = User.objects.all()
return ''
@register.tag(name="get_all_users")
def get_all_users(parser, token):
# First break up the arguments that have been passed to the template tag
bits = token.contents.split()
if len(bits) != 3:
raise TemplateSyntaxError, "get_all_users tag takes exactly 2 arguments"
if bits[1] != 'as':
raise TemplateSyntaxError, "1st argument to get_all_users tag must be 'as'"
return GetAllUsers(bits[2])
精彩评论