Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom mixin in django?

Tags:

python

django

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?

like image 836
Niladry Kar Avatar asked Feb 08 '19 12:02

Niladry Kar


People also ask

What is the use of mixin in Django?

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?

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.

What is mixin programming?

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.

Can a mixin inherit from another mixin?

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.


1 Answers

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):

    # ...
like image 180
Willem Van Onsem Avatar answered Sep 19 '22 23:09

Willem Van Onsem