Django Passing list of objects to template

2019-07-03 05:24发布

问题:

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")

I tried this:

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.

回答1:

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.

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).

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.



回答2:

Try adding brackets to the function call maybe?

'profiles': get_profiles()

Otherwise you are just passing a reference to the function object.

But the problem is this would only be evaluated once, when urls.py is called.

Why not make a view function to correspond with the url 'users/'?



回答3:

get_profiles(), with parentheses