【问题标题】:Django templatetag User objects includedDjango templatetag 包含的用户对象
【发布时间】:2011-08-18 08:03:36
【问题描述】:

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

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)

当我使用此代码时

{% 加载 getusers %} {% get_all_users 作为所有用户 %} {% for user in allusers %} {{用户}} {% endfor %}

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

追溯

追溯: get_response 中的文件“/usr/lib/python2.7/site-packages/django/core/handlers/base.py” 111. 响应 = 回调(请求,*callback_args,**callback_kwargs) _wrapped_view 中的文件“/usr/lib/python2.7/site-packages/django/contrib/auth/decorators.py” 23. return view_func(request, *args, **kwargs) 撰写中的文件“/home/ajunkkil/Django/basedraft/messages/views.py” 91. }, context_instance=RequestContext(request)) render_to_response 中的文件“/usr/lib/python2.7/site-packages/django/shortcuts/__init__.py” 20. 返回 HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) render_to_string 中的文件“/usr/lib/python2.7/site-packages/django/template/loader.py” 188. 返回 t.render(context_instance) 渲染中的文件“/usr/lib/python2.7/site-packages/django/template/base.py” 123.返回self._render(上下文) _render 中的文件“/usr/lib/python2.7/site-packages/django/template/base.py” 117.返回self.nodelist.render(上下文) 渲染中的文件“/usr/lib/python2.7/site-packages/django/template/base.py” 744. bits.append(self.render_node(节点,上下文)) render_node 中的文件“/usr/lib/python2.7/site-packages/django/template/debug.py” 73. 结果 = 节点渲染(上下文) 渲染中的文件“/usr/lib/python2.7/site-packages/django/template/loader_tags.py” 127. 返回已编译的_parent._render(上下文) _render 中的文件“/usr/lib/python2.7/site-packages/django/template/base.py” 117.返回self.nodelist.render(上下文) 渲染中的文件“/usr/lib/python2.7/site-packages/django/template/base.py” 744. bits.append(self.render_node(节点,上下文)) render_node 中的文件“/usr/lib/python2.7/site-packages/django/template/debug.py” 73. 结果 = 节点渲染(上下文) 渲染中的文件“/usr/lib/python2.7/site-packages/django/template/loader_tags.py” 127. 返回已编译的_parent._render(上下文) _render 中的文件“/usr/lib/python2.7/site-packages/django/template/base.py” 117.返回self.nodelist.render(上下文) 渲染中的文件“/usr/lib/python2.7/site-packages/django/template/base.py” 744. bits.append(self.render_node(节点,上下文)) render_node 中的文件“/usr/lib/python2.7/site-packages/django/template/debug.py” 73. 结果 = 节点渲染(上下文) 渲染中的文件“/usr/lib/python2.7/site-packages/django/template/loader_tags.py” 64. 结果 = block.nodelist.render(上下文) 渲染中的文件“/usr/lib/python2.7/site-packages/django/template/base.py” 744. bits.append(self.render_node(节点,上下文)) render_node 中的文件“/usr/lib/python2.7/site-packages/django/template/debug.py” 73. 结果 = 节点渲染(上下文) 渲染中的文件“/usr/lib/python2.7/site-packages/django/template/loader_tags.py” 64. 结果 = block.nodelist.render(上下文) 渲染中的文件“/usr/lib/python2.7/site-packages/django/template/base.py” 744. bits.append(self.render_node(节点,上下文)) render_node 中的文件“/usr/lib/python2.7/site-packages/django/template/debug.py” 73. 结果 = 节点渲染(上下文) 渲染中的文件“/home/ajunkkil/Django/basedraft/messages/templatetags/getusers.py” 19. 上下文[self.varname] = User.objects.all() __setitem__ 中的文件“/usr/lib/python2.7/site-packages/django/template/context.py” 53. self.dicts[-1][key] = 值 异常类型:/messages/compose/ 处的 TemplateSyntaxError 异常值:渲染时捕获 TypeError:不可散列的类型:'list'

【问题讨论】:

  • 必须在所有模板中还是仅在一个模板中?
  • 合二为一,它是一个用于撰写新消息的模板,我希望将用户列表放在其中。

标签: django django-templates


【解决方案1】:

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

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

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

return GetAllUsers(bits)

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

return GetAllUsers(bits[2])

但是,最后,如果这只是针对一个模板,我不明白您为什么不按照程序员手册的建议在视图中执行此操作。

【讨论】:

【解决方案2】:

如果在上下文中这样做可能更好,不要看到使用标签的意义

查看:

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 %}

【讨论】:

  • stackoverflow.com/questions/5867451/… 。这就是我最初想要做的,我不知道如何让我的用户对象到“撰写”网址并在那里列出它们。所以当我有一个 url url(r'^compose/$', compose, name='messages_compose') 时,我可以使用 render_to_response 来获取用户对象吗?
  • 如果我理解正确,当确定时,render_to_response 将加载并解析模板并返回一个有效的 HttpResponse 对象
【解决方案3】:

您是否尝试过使用inclusion tag

据我了解,它似乎介于simple tagassignment tag Daniel 提到的之间。这意味着 数据不会像简单标签那样直接输出。在assignment tag 将数据存储在变量中的地方,您直接迭代包含标签需要一个模板 sn-p 来呈现数据。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 2011-12-17
    • 2019-08-31
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多