Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

Django Pass Multiple Models to one Template

I am building an address book that includes the relationships between entries, etc. I have separate models for Individuals, Companies, Venues, and Roles. On my index page I would like to list all of the instances of each model and then filter them. So that a person could easily search and find an entry. I have been able to list a single model using generic views and use get_extra_context to show one more model:

#views.py

 class IndividualListView(ListView):

    context_object_name = "individual_list"
    queryset = Individual.objects.all()
    template_name='contacts/individuals/individual_list.html'


class IndividualDetailView(DetailView):

    context_object_name = 'individual_detail'
    queryset = Individual.objects.all()
    template_name='contacts/individuals/individual_details.html'

    def get_context_data(self, **kwargs):
        context = super(IndividualDetailView, self).get_context_data(**kwargs)
        context['role'] = Role.objects.all()
        return context

I am also able to list a single model using a custom view:

#views.py
def object_list(request, model):
    obj_list = model.objects.all()
    template_name = 'contacts/index.html'
    return render_to_response(template_name, {'object_list': obj_list}) 

Here are the urls.py for both of these tests:

(r'^$', views.object_list, {'model' : models.Individual}),

(r'^individuals/$', 
    IndividualListView.as_view(),
        ),
(r'^individuals/(?P<pk>d+)/$',
    IndividualDetailView.as_view(),

         ),

So my question is "How do I modify this to pass more then one model to the template?" Is it even possible? All of the similar questions on StackOverflow only ask about two models (which can be solved using get_extra_context).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I ended up modifying @thikonom 's answer to use class-based views:

class IndexView(ListView):
    context_object_name = 'home_list'    
    template_name = 'contacts/index.html'
    queryset = Individual.objects.all()

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['roles'] = Role.objects.all()
        context['venue_list'] = Venue.objects.all()
        context['festival_list'] = Festival.objects.all()
        # And so on for more models
        return context

and in my urls.py

url(r'^$', 
    IndexView.as_view(),
    name="home_list"
        ),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...