Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am new to Django, and I usually used function-based views. But I see that using mixins with class-based views way more powerful. I did a lot of research but I am still confused about how to use Mixins. How come Mixins are an excellent way of reusing code across multiple classes?

When or Why I should use class-based views?

If you show me an example or better way of explanation than it does in docs, I would be appreciated.

like image 849
mr_nocoding Avatar asked Oct 12 '25 11:10

mr_nocoding


1 Answers

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.

like image 189
Dimitar Avatar answered Oct 14 '25 05:10

Dimitar