【问题标题】:Django Passing list of objects to templateDjango将对象列表传递给模板
【发布时间】:2011-08-17 13:40:08
【问题描述】:

我无法在与此处的 r'^compose/$' 相同的模板中传递我的 get_profiles。 r'^users/$' 是我用作模型的东西,它可以工作。 “compose”是我views.py中的一个函数。

从 django.conf.urls.defaults 导入 * 从 django.views.generic.simple 导入 redirect_to 从 django.views.generic.simple 导入 direct_to_template 从messages.views导入* 从 userprofile.views 导入 get_profiles urlpatterns = 模式('', url(r'^$', redirect_to, {'url': 'inbox/'}), url(r'^inbox/$', 收件箱, name='messages_inbox'), url(r'^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' }), ) 用户配置文件/views.py def get_profiles(): 返回 Profile.objects.order_by("user")

我试过这个:

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

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

【问题讨论】:

    标签: django django-templates django-urls


    【解决方案1】:

    尝试在函数调用中添加括号?

    'profiles': get_profiles()
    

    否则,您只是传递对函数对象的引用。

    但问题是这只会被评估一次,当调用 urls.py 时。

    为什么不创建一个与 url 'users/' 对应的视图函数呢?

    【讨论】:

    • get_profiles() 还给出了“函数”对象不可迭代。使视图功能与 url 用户相对应是什么意思?如何?我可以在我的“撰写”中写一些东西,以在 compose.html 中生成我的用户列表。最终它是一个消息编辑器,我希望用户在编写时可见。
    【解决方案2】:

    get_profiles(),带括号

    【讨论】:

      【解决方案3】:

      正如其他人所说,您需要实际调用该函数,但如果您在 urls.py 中执行此操作,则每个进程只会评估一次。你不想那样做。

      你没有展示get_profiles 做了什么,但我认为它是某种实用函数。我倾向于认为它们属于一个单独的文件,lib.pyutils.py,而不是views.py。 (也就是说,假设它实际上不是一个视图本身 - 如果是,那么您需要重新考虑您的整个方法。

      但是,我认为您实际上需要做的是制作一个模板标签。如果愿意,您可以将逻辑保留在get_profiles 中,然后制作一个调用该函数的简单标记。那么你就不需要在extra_context 中传递数据了——只需将标签添加到你的模板中。

      【讨论】:

      • 编辑了帖子。 get_profiles 只返回我的 Profile 对象。我想在模板中列出这些以及我的撰写信息。你能详细说明制作模板标签吗?我会搜索这个。
      • docs.djangoproject.com/en/1.3/howto/custom-template-tags - 请特别参阅关于在上下文中设置变量的部分。请注意,它似乎比实际更复杂。
      猜你喜欢
      • 2012-09-27
      • 2014-08-14
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多