[Django]-Can you show me an example of Mixins with class-based views in Django? What is the usage?

5👍

I think the documentation for that is perfect: https://docs.djangoproject.com/en/3.1/topics/class-based-views/mixins/

That’s how I used mixins so far.

Models

For models: Lets say that you want to have created_at, updated_at fields in every model that you have. I would create a TimestampableMixin where it could look like this.

(https://docs.djangoproject.com/en/3.1/topics/db/models/#abstract-base-classes) (why abstract?)


class TimestampableMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True 

And then I would just extend my other models with the mixin. All of the models which are inheriting the TimestampableMixin will have those fields included in them. Keep in mind that you can add more mixins into that Post Model, like TaggingMixin etc.

class Post(TimestampableMixin, TaggingMixin):
    ...

Views

I don’t find myself using them in my views often but one time I’ve used them for repeatedly getting the same context_data and some kwargs from the url.

So I created a DashboardMixin with the following implemented methods.

class DashboardMixin:

    def get_context_data(self):
        ...

# and then in the Views
class IndexView(DashboardMixin, View):
    ...

Keep in mind the MRO(Method Resolution Order)! – That’s how python handles multiple inheritance.

That’s how I used mixins within Django. You can apply that in almost every aspect of the framework. Eg. in the django’s admin site, extending and adding more functionality to the ModelAdmin, in Forms and so on. The documentation that I linked is explaining all of that you will get a better idea when you read it.

Leave a comment