[Django]-Can I combine Create and List class based generic views using mixins?

6๐Ÿ‘

โœ…

Note: I no longer advocate this solution, as this is a much cleaner one.

By trial and error (and looking at Django source), I wrote this:

class ListCreateView(ListView, BaseCreateView):
    def get_context_data(self, **kwargs):
        self.object = None
        self.object_list = self.get_queryset()

        form_class = self.get_form_class()
        form = self.get_form(form_class)

        kwargs.update({'object_list': self.object_list, 'form': form})

        context = super(ListCreateView, self).get_context_data(**kwargs)
        return context

Works fine both for creating and listing (although it may issue a few extra database calls, not sure).

๐Ÿ‘คDan Abramov

Leave a comment