2

I'm starting with django (and stackoverflow!)

I've been trying to create a webpage with a form and a list of items. ( Django - Mixing ListView and CreateView). I came up with a solution but I'm not convinced by my code!

I'm using Django mixin BaseCreateView and BaseListView to generate the form and list context data. But because it's views, they call directly render_to_response().

So I overloaded the get() method to manually call both parents methods and extract the context data. Then I called render_to_response() myself.

class FormAndListView(BaseCreateView, BaseListView, TemplateResponseMixin):
    def get(self, request, *args, **kwargs):
        formView = BaseCreateView.get(self, request, *args, **kwargs) # formView contains a response_class
        listView = BaseListView.get(self, request, *args, **kwargs)   # listView contains a response_class as well...
        formData = formView.context_data['form']                      # extract the form from the response_class 
        listData = listView.context_data['object_list']               # extract the object list from the response_class

        return render_to_response('textfrompdf/index.html', {'form' : formData, 'all_PDF' : listData},
                           context_instance=RequestContext(request))

On one hand I'm not re-writing what is already in the mixin to manage forms and lists of items... On the other hand, django is calculating the whole render_to_response() 3 times!

What would be the clean Django-way to write this page?

Community
  • 1
  • 1
Nico
  • 292
  • 1
  • 2
  • 9
  • 1
    If you are just starting out with Django, use plain old functions for views. Figure out how it works there before taking on the new class-based views. – Brian Neal Feb 19 '12 at 03:17

1 Answers1

1
class FormAndListView(BaseCreateView, BaseListView, TemplateResponseMixin):

    def render_to_response(context, **responsekwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = {}
        context.update( BaseCreateView.get(self, request, *args, **kwargs) ) # formView contains a response_class
        context.update( BaseListView.get(self, request, *args, **kwargs) )  # listView contains a response_class as well...

        return TemplateResponseMixin.render_to_response('textfrompdf/index.html', context,
                           context_instance=RequestContext(request))
Thomas
  • 11,757
  • 4
  • 41
  • 57