Django将对象列表传递给模板 [英] Django Passing list of objects to template

查看:151
本文介绍了Django将对象列表传递给模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我有麻烦地将我的get_profiles传递到与r'^ compose / $'相同的模板中。 r'^ users / $'是我正在使用的一个模型,它的工作原理。 compose是我的views.py中的一个函数。

I have trouble of passing my get_profiles in the same template as r'^compose/$' here. r'^users/$' is what I'm using as a model and it works. "compose" is a function in my views.py.


from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
from django.views.generic.simple import direct_to_template

from messages.views import *

from userprofile.views import get_profiles

urlpatterns = patterns('',
    url(r'^$', redirect_to, {'url': 'inbox/'}),
    url(r'^inbox/$', inbox, name='messages_inbox'),
    url(r'^outbox/$', outbox, name='messages_outbox'),
    url(r'^compose/$', compose, name='messages_compose'),
    url(r'^users/$', direct_to_template, {'extra_context': { 'profiles': get_profiles }, 'template': 'messages/users.html' }),
)




userprofile/views.py
def get_profiles():
    return Profile.objects.order_by("user")

我尝试过:


url(r'^compose/$', compose, direct_to_template, {'extra_context': { 'profiles': get_profiles },  'template': 'messages/compose.html' }),

但是我得到一个函数对象是不可迭代的。

But I get a function object is not iterable.

推荐答案

正如其他人所说,你需要实际调用这个函数,但是如果你在urls.py中这样做只会每个进程评估一次。你不想这样做。

As others have said, you need to actually call the function, but if you do that in urls.py it will only be evaluated once per process. You don't want to do that.

你不会显示什么 get_profiles ,但我认为它是某种效用函数。我倾向于认为这些属于独立的文件 lib.py utils.py 而不是视图。 PY。 (也就是说,假设它实际上不是一个视图 - 如果是,那么你需要重新思考你的整个方法)。

You don't show what get_profiles does, but I assume it's some sort of utility function. I tend to think that those belong in a separate file, lib.py or utils.py, rather than views.py. (That is, assuming it's not actually a view itself - if it is, then you'll need to rethink your whole approach).

然而,我认为你实际上是需要做的是做一个模板标签。如果您喜欢,可以将逻辑保留在 get_profiles 中,然后创建一个调用该函数的简单标签。然后,您不需要在 extra_context 中传递数据,只需将标记添加到模板中。

However, what I think you actually need to do is to make a template tag instead. You can keep the logic in get_profiles if you like, then make a simple tag that calls that function. Then you don't need to mess about with passing data in extra_context - just add the tag to your template.

这篇关于Django将对象列表传递给模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆