用户对象的Django模板标签
我想通过模板标签将用户对象传递给我的模板。我第一次尝试simple_tag,但显然它只适用于字符串?反正这是我到目前为止有:用户对象的Django模板标签
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)
这是我在我的模板来测试它:
{% load profiles %}
{% get_profiles %}
{% for p in get_profiles %} {{ p }} {% endfor %}
我只得到[, , , , ]
打印出来或者如果我将User.objects.all()
更改为User.objects.count()
,我会得到正确的号码。我的模板中的迭代似乎没有做任何事情。哪里不对?
什么是格式字符串?你需要调用模板标签是这样的:
{% get_all_users as allusers %}
{% for user in allusers %}
{{ user.first_name }}
{% endfor %}
所以你需要一个模板标签一样
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])
{%get_all_users as alluserrs%} 这给了我一个Caught TypeError而渲染:不可用类型:'列表'。我在{get_all_users%} {{user}} {%endfor%}中尝试了{%。它不会抱怨,但它也不会打印任何东西。 – leffe 2011-05-04 07:41:19
谢谢你的帮助!我不得不改变返回GetAllUsers(bits) 返回GetAllUsers(bits [2]),否则它是完美的。再次感谢! – leffe 2011-05-04 08:52:24
啊是啊,编辑帖子反映! – 2011-05-04 08:58:22
User.objects.get(用户名=“测试”)给我的用户“测试”正确也。正当我尝试传递所有对象并迭代时,我不会在模板中获取任何与循环有关的东西。 – leffe 2011-05-03 14:52:32