Django将对象列表传递给模板

编程入门 行业动态 更新时间:2024-10-24 23:27:12
本文介绍了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将对象列表传递给模板

本文发布于:2023-10-07 17:30:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1470033.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   模板   列表   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!