Issue
I have a custom Django mixin which should be imported/added to a view class only if some app is installed, e.g.
class MyView(LoginRequiredMixin, CustomMixin, View):
# ^
# this is an optional mixin
pass
How to achieve this in Django?
Solution
The parameter list passed to a class definition in Python 3 supports all of the features of a function call, meaning you can use *args
and **kwargs
-style arguments in the class base list:
bases = [LoginRequiredMixin]
if apps.is_installed("some_app"):
bases.append(CustomMixin)
class MyView(*bases, View):
...
Alternatively, you can use a metaclass:
from django.apps import apps
class MixinsMeta(type):
def __new__(cls, name, bases, namespace, **kwargs):
# customize the `bases` tuple here..
return super().__new__(cls, name, bases, namespace)
Then in the view:
class MyView(View, metaclass=MixinsMeta):
...
Answered By - Eugene Yarmash
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.