[Django]-How do I apply Mixins to all CBVs in a django app?

3👍

Your approach is good. I’ve been doing so for some projects with a slight difference:

myapp/views/generic.py

from django.views.generic import (
    CreateView as BaseCreateView,
    DetailView as BaseDetailView,
    UpdateView as BaseUpdateView,
    DeleteView as BaseDeleteView,
)

__all__ = ['MyappMixin', 'CreateView', 'DetailView', 'UpdateView', 'DeleteView']


class MyappMixin(LoginRequiredMixin, UserpermissionMixin):
    pass


class CreateView(MyappMixin, BaseCreateView):
    pass


class DetailView(MyappMixin, BaseDetailView):
    pass


class UpdateView(MyappMixin, BaseUpdateView):
    pass


class DeleteView(MyappMixin, BaseDeleteView):
    pass

myapp/views/base.py

from .generic import CreateView

class MyCreateView(CreateView):
    pass

It works fine, without much hassle, and allows you to easily skip the mixin exceptionally if needed.

According to the usecase, another solution might be to use middlewares or context processors.

class MyMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        is_in_myapp = request.resolver_match.app_name == 'myapp'
        if is_in_myapp and not request.user.is_authenticated:
            response = HttpResponse("Permission denied", status=403)
        else:
            response = self.get_response(request)
        return response

Leave a comment