理解Django基于类的视图mixins

时间:2014-03-02 08:29:37

标签: python django

基于Django Class Based View的mixins是什么?如何开始使用这个和什么时候?任何人都可以提供实用的例子来让我理解它吗?

1 个答案:

答案 0 :(得分:4)

您是否阅读过https://docs.djangoproject.com/en/dev/topics/class-based-views/mixins/

我不确定我的例子是否相关,但它是我经常使用的混合...

class OwnedObjectsMixin(object):

    def form_valid(self, form):
        form.instance.owner = self.request.user
        form.full_clean()
        if form.is_valid():
            return super(OwnedObjectsMixin, self).form_valid(form)
        else:
            return super(OwnedObjectsMixin, self).form_invalid(form)

    def get_queryset(self):
        self.user_id = self.request.user.id
        return self.model.objects.filter(owner=self.user_id)


class MyModelList(OwnedObjectsMixin, ListView):
    model = myModel