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]
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With