开发者

Can I combine Create and List class based generic views using mixins?

I'm looking for the easiest way to combine List and Create functionally with generic class views.

I want to have a page that has an item list and a form to add a new item on the bottom.

I thought that mixin architecture would allow to com开发者_开发问答bine necessary classes but I had no luck yet.

This almost works:

class ResourceListView(ListView, BaseCreateView):
    context_object_name = 'resources'
    model = Resource
    form_class = ResourceForm

But form isn't accessible inside template and the thing crashes on invalid output (when form is valid, it's fine).

This may have to do with multiple inheritance but I'm not really into Python yet so it gets too confusing.

Is there a simple way to combine some of the mixins into a view-and-create View, or do I have to roll out my own?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜