Thứ Bảy, 2 tháng 3, 2019

What is Mixin suffix class in Django?

A Mixin is a Class which contains a combinations of methods from other Classes

Why i need a Mixin class?

  1. You want to provide a lot of optional features for a class.
  2. You want to use one particular feature in a lot of different classes.


This is simple example about Claxx Mixin from Mixin Documentation on
# Define a simple class mixin
from django.http import JsonResponse

class JSONResponseMixin(object):
    A mixin that can be used to render a JSON response.
    def render_to_json_response(self, context, **response_kwargs):
        Returns a JSON response, transforming 'context' to make the payload.
        return JsonResponse(

    def get_data(self, context):
        Returns an object that will be serialized as JSON by json.dumps().
        # Note: This is *EXTREMELY* naive; in reality, you'll need
        # to do much more complex handling to ensure that arbitrary
        # objects -- such as Django model instances or querysets
        # -- can be serialized as JSON.
        return context
And, we can easy use:
from django.views.generic import TemplateView

class JSONView(JSONResponseMixin, TemplateView):
    def render_to_response(self, context, **response_kwargs):
        return self.render_to_json_response(context, **response_kwargs)