[Django]-Understanding Django Class-based views mixins

6👍

Have you read https://docs.djangoproject.com/en/dev/topics/class-based-views/mixins/ ?

I’m not sure my example is relevant but it is a mixin I regularly use…

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

Leave a comment