Django templatetag包含用户对象

时间:2011-05-04 08:10:14

标签: django django-templates

嘿,我现在一直在努力解决这个问题。我试图将我的用户对象传递给模板,以便我可以列出它们,或列出用户名。感谢我从这里得到的帮助到目前为止我有这个。

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

register = Library()

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)

#register.tag('get_all_users', get_all_users)

当我将此代码与

一起使用时
{% load getusers %} 
{% get_all_users as allusers %}
{% for user in allusers %}
     {{ user }}
{% endfor %}

在我的模板中,我在渲染时遇到了Caught TypeError:unhashable type:'list'。它特别是{%get_all_users as allusers%}导致它。我尝试了{%for user in get_all_users%},它会通过,但不会打印任何内容。

回溯

Traceback:
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)
File "/home/ajunkkil/Django/basedraft/messages/views.py" in compose
  91.     }, context_instance=RequestContext(request))
File "/usr/lib/python2.7/site-packages/django/shortcuts/__init__.py" in render_to_response
  20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  188.         return t.render(context_instance)
File "/usr/lib/python2.7/site-packages/django/template/base.py" in render
  123.             return self._render(context)
File "/usr/lib/python2.7/site-packages/django/template/base.py" in _render
  117.         return self.nodelist.render(context)
File "/usr/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/usr/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/usr/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "/usr/lib/python2.7/site-packages/django/template/base.py" in _render
  117.         return self.nodelist.render(context)
File "/usr/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/usr/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/usr/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "/usr/lib/python2.7/site-packages/django/template/base.py" in _render
  117.         return self.nodelist.render(context)
File "/usr/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/usr/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/usr/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "/usr/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/usr/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/usr/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "/usr/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/usr/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/home/ajunkkil/Django/basedraft/messages/templatetags/getusers.py" in render
  19.         context[self.varname] = User.objects.all()
File "/usr/lib/python2.7/site-packages/django/template/context.py" in __setitem__
  53.         self.dicts[-1][key] = value

Exception Type: TemplateSyntaxError at /messages/compose/
Exception Value: Caught TypeError while rendering: unhashable type: 'list'

3 个答案:

答案 0 :(得分:3)

如果您使用的是最新的开发版本,则会有一个新的标记快捷方式assignment tags,它会为您完成所有这些操作。然后你可以这样做:

@register.assignment_tag
def get_all_users():
    return User.objects.all()

您的代码的实际问题是您将整个参数列表传递给标记实例化:

return GetAllUsers(bits)

当你应该传递包含变量名的位时:

return GetAllUsers(bits[2])

但是,最后,如果这仅适用于一个模板,我不明白你为什么不在视图中这样做,正如programmersbook建议的那样。

答案 1 :(得分:0)

您是否尝试使用inclusion tag

根据我的理解,它似乎位于simple tagassignment tag丹尼尔之间。这意味着 数据不像简单标签那样直接输出。如果assignment tag将数据存储在您直接迭代包含标记的变量中,则需要一个模板片段来呈现数据。

@register.inclusion_tag('users.html')
def show_users():
    users = user.objects.all()
    return {'users': users}

然后,您可以编写一个模板摘要(users.html),准确呈现您的用户列表部分。

答案 2 :(得分:0)

如果在上下文中执行此操作可能更好,请注意不要使用标记

视图:

from django.contrib.auth.models import User
from django.shortcuts               import render_to_response

def users(request):
    user_list = User.objects.all()

    ctx = {'user_list':user_list}

    render_to_response('temp.html', ctx)
模板中的

{% for user in user_list %}
    {{ user }}
{% endfor %}