djangoinheritancemixinsdispatch

How to make Class Based View mixin's dispatch method fire first?


I have a Django Class Based View that overrides the dispatch method.

I want to add a mixin to this Class Based View.

The mixin also overrides the dispatch method.

Is it possible to have the mixins dispatch method execute before the Class Based Views custom dispatch method? If so, how would I implement this ?

Currently, when I implement my solution, as in the following example, the CustomerCreateView's custom dispatch method fires first, which is not what I need.

class MyMixin(LoginRequiredMixin):
    def dispatch(self, request, *args, **kwargs):
        ....
    return super().dispatch(request, *args, **kwargs)


class CustomerCreateView(MyMixin, CreateView):
    model = Customer
    form_class = CreateCustomerForm
    title = "Add a New Customer"

    def dispatch(self, request, *args, **kwargs):
        ...
        return super().dispatch(request, *args, **kwargs)

Solution

  • MyMixin is CustomerCreateView's superclass. So CustomerCreateView.dispatch will always be called first. But you can call MyMixin.dispatch yourself before running the rest of the method:

    class CustomerCreateView(MyMixin, CreateView):
        model = Customer
        form_class = CreateCustomerForm
        title = "Add a New Customer"
    
        def dispatch(self, request, *args, **kwargs):
            # Call MyMixin.dispatch
            response = super().dispatch(request, *args, **kwargs)
            # Do other stuff
            ...
            return response
    

    Alternatively, you can rearrange the inheritance:

    class MyMixin(LoginRequiredMixin):
        def dispatch(self, request, *args, **kwargs):
            ...
            return super().dispatch(request, *args, **kwargs)
    
    
    class CustomerCreateView(CreateView):
        model = Customer
        form_class = CreateCustomerForm
        title = "Add a New Customer"
    
        def dispatch(self, request, *args, **kwargs):
            ...
            return super().dispatch(request, *args, **kwargs)
    
    class CorrectView(MyMixin, CustomerCreateView):
        # MyMixin.dispatch will be called first