Search code examples
djangoajaxdjango-viewflow

Overriding django viewflow views to return JSON


Probably something basic, but cannot seem to figure it out.

I am trying to implement a custom UI for viewflow where the various tasks are displayed as modals. I have managed to get the initial start view to display in a modal and to use AJAX to submit the form. I would like to get all the other process task views to do the same. The following is my attempt based on this answer however, the overridden view AJAXDetailTaskView(DetailTaskView) does not seem to get called and I am wondering where I am going wrong.

In this specific instance I am trying to modify the start detail view (which I presume will be the same principle for all the other views)

flows.py

class AssetFlow(Flow):

    process_class = models.AssetProccess
    task_class = models.AssetTask
    lock_impl = select_for_update_lock

    start = (
        flow.Start(
            views.StartView)
        .Permission(auto_create=True)
        .Next(this.co_approval)
    )

    co_approval = (
        flow.View(
            views.AssetView
        )
        .Next(this.finance_tc)
    )

...

views.py

from viewflow.flow.views.detail import DetailTaskView

class AJAXDetailTaskView(DetailTaskView):
    def render_to_response(self, context, **response_kwargs):

        if self.request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
            print('An AJAX request')
            return JsonResponse('Success', safe=False, **response_kwargs)
        else:
            print('Not an AJAZ request')
            return super(AJAXDetailTaskView, self).render_to_response(context, **response_kwargs)

class StartView(StartFlowMixin, generic.UpdateView, flow.View):
    model = models.Item
    form_class = forms.AssetForm
    data = dict()
    detail_view_class = AJAXDetailTaskView

    def get_object(self):
        return self.activation.process.asset

    def get(self, request, *args, **kwargs):

        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        context = self.get_context_data(form=form, data=self.data)
        html_form = render_to_string('asset/asset/partial_start.html',
                                     context,
                                     request=request,
                                     )
        return JsonResponse({'html_form': html_form})
        
...

Solution

  • detail_view_class is an attribute of flow.Start not the StartView