Django - 2 views in one template

I have 2 different views that get filtered data from db. and I have to use these views in one template file (admin.html), but I cannot use multiple views on the page at the same time.

here is my look1:

draft_list = Post.objects.filter(isdraft=True).order_by("-posted") return render_to_response('userside/admin.html', {'draft_list':draft_list,}, context_instance = RequestContext(request)) 

view2:

 publish_list = Post.objects.filter(isdraft=False).order_by("-posted") return render_to_response('userside/admin.html', {'publish_list':publish_list,}, context_instance = RequestContext(request)) 

I like to use them like:

 {% for d in draft_list %} {{ d.title }} {% endfor %} -- {% for p in publish_list %} {{ p.title }} {% endfor %} 

I want to make these 2 presentations โ€œat a glanceโ€. What is the right way?

+4
source share
2 answers

You do not want to have 2 views in 1 template (which is impossible in any case), but there are 2 models available in 1 template for rendering. Just do it like this:

 draft_list = Post.objects.filter(isdraft=True).order_by("-posted") publish_list = Post.objects.filter(isdraft=False).order_by("-posted") return render_to_response('userside/admin.html', {'draft_list':draft_list,'publish_list':publish_list}) 
+13
source

From your question, it seems that you are using view-based functions. An alternative way to solve the problem you have is to use class-based views and override the get_context_data method to pass the template two contexts, one for each request.

 #views.py class MyClassBasedView(DetailView): context_object_name = 'draft_list' template='my-template' queryset = Post.objects.filter(isdraft=True).order_by("-posted") def get_context_data(self, **kwargs): context = super(MyClassBasedView, self).get_context_data(**kwargs) context['publish_list'] = Post.objects.filter(isdraft=False).order_by("-posted") return context 
0
source

All Articles