Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mixins in class based view - Django

So I started using the generic class based views and I gotta say, they do save time. But I was wondering whether I could use mixins to provide generic impl rather than having to code in each view. for e.g. I have a ListView and DetailView. To restrict the listing and editing, I could override the get_queryset() and filter it by the logged in user. But as you guessed, i would have to do that in each view,

class JediListView(ListView):
    def get_queryset(self):
        q = <call super>.filter(user=request.user) #assume i have 'login_required' in the urls

class JediDetailView(DetailView):
    def get_queryset(self):
        q = <call super>.filter(user=request.user) #assume i have 'login_required' in the urls

I could create a new parent class for each of the view but I would still be repeating the code.

class RepublicListView(ListView):
     # override get_queryset code as above

class JediListView(RepublicListView):

# repeat fot DetailView, DeleteView, UpdateView

I was wondering about mixins, I am exactly sure how mixins work [from java background, so I am awed and fearful at the same time]

like image 239
Saikiran Yerram Avatar asked Jan 22 '13 02:01

Saikiran Yerram


2 Answers

You actually almost found the answer by yourself. You can write the following Mixin:

class UserFilterMixin:
    def get_queryset(self):
        return <call super>.filter(user=self.request.user)

And then use it in the classes like this:

class RepublicListView(LoginRequiredMixin, UserFilterMixin, ListView):

And so on for the other classes...

like image 143
melbic Avatar answered Nov 15 '22 07:11

melbic


You can use LoginRequiredMixin from django-braces.

from django.views.generic import ListView, DetailView

from braces.views import LoginRequiredMixin


class JediListView(LoginRequiredMixin, ListView):
    model = JediModel


class JediDetailView(LoginRequiredMixin, Detail):
    model = JediModel

As per Chapter-8: Best Practices for Class-Based Views from TWO SCOOPS of DJANGO,

THIRD-PARTY PACKAGES: CBVs + django-braces Are Great Together We feel that django-braces is the missing component for Django CBVs. It provides a set of clearly coded mixins that make Django CBVs much easier and faster to implement. !e next few chapter will demonstrate it's mixins in various code examples.

like image 33
pankaj28843 Avatar answered Nov 15 '22 09:11

pankaj28843