I have a decorator which prevents the user from accessing URLs if the product with id=1
is not activated.
I want to create a mixin similar to this.
This is my decorator:
from django.core.exceptions import PermissionDenied
from ecommerce_integration.models import Product
def product_1_activation(function):
def wrap(request, *args, **kwargs):
products = Product.objects.filter(pk=1, activate=True)
if products:
return function(request, *args, **kwargs)
else:
raise PermissionDenied
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
Any idea how to create a custom mixin similar to the above decorator?
Actually I want to create mixins for my Class Based View.
Can anyone help me out in this?
In object-oriented programming languages, a mixin is a class which contains a combination of methods from other classes. Add timestamp and trashed attribute for every model object - This was one of the most important thing that we should have been implemented as early as possible.
What is a mixin in Python. A mixin is a class that provides method implementations for reuse by multiple related child classes. However, the inheritance is not implying an is-a relationship. A mixin doesn't define a new type. Therefore, it is not intended for direction instantiation.
Mixins are a language concept that allows a programmer to inject some code into a class. Mixin programming is a style of software development, in which units of functionality are created in a class and then mixed in with other classes. A mixin class acts as the parent class, containing the desired functionality.
It's perfectly valid for a mixin to inherit from another mixin - in fact, this is how most of Django's more advanced mixins are made. However, the idea of mixins is that they are reusable parts that, together with other classes, build a complete, usable class.
We can make a Mixin
that just overrides the dispatch
method, like:
class ProductExistsRequiredMixin:
def dispatch(self, request, *args, **kwargs):
if Product.objects.filter(pk=1, activate=True):
return super().dispatch(request, *args, **kwargs)
else:
raise PermissionDenied
and then use it in a view like:
class MyCustomView(ProductExistsRequiredMixin, View):
# ...
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