Django.fun

how do i combine two template views into on single view here?

I have implemented two views to display data according to the choice_fields but i have two views with slightly different logic in views and templates how do i combine them into one so that i take care of DRY

views.py:

class View1(LoginRequiredMixin,TemplateView):
    template_name = 'temp1.html'
    
    def get_context_data(self, **kwargs):
        context =  super(View1,self).get_context_data(**kwargs)
        context['progress'] = self.kwargs.get('progress', 'in_progress')
        if context['progress'] == 'in_progress':
            context['objects'] = Model.objects.filter(progress='in_progress')
        else:
            context['objects'] = Model.objects.filter(progress__iexact=context['progress'], accepted=self.request.user)
        return context



class View2(LoginRequiredMixin,TemplateView):
    template_name = 'temp2.html'
    
    def get_context_data(self, **kwargs):
        context =  super(View2,self).get_context_data(**kwargs)
        context['progress'] = self.kwargs.get('progress', 'in_progress')
        if context['progress'] == 'in_progress':
            context['objects'] = Model.objects.filter(progress='in_progress',created = self.request.user)
        else:
            context['objects'] = Model.objects.filter(progress__iexact=context['progress'], created_by=self.request.user)
        return context

Answers: 1

Answered by nigel222, Nov. 25, 2021, 1:12 p.m.

Implement something like get_queryset in Class-based views.

class BaseView(LoginRequiredMixin,TemplateView):
    """ requires subclassing to define template_name and 
        update_qs( qs, progress) method """

    def get_context_data(self, **kwargs):
        context =  super(View1,self).get_context_data(**kwargs)
        progress = self.kwargs.get('progress', 'in_progress')

        if progress == 'in_progress':
            qs = Model.objects.filter(progress='in_progress')
        else:
            qs = Model.objects.filter(progress__iexact=context['progress'] )

        qs = self.update_qs( qs, (progress == 'in_progress') )

        context['progress'] = progress
        context['objects'] = qs
        return context

class View1( BaseView):
    template_name = 'temp1.html'

    def update_qs( self, qs, in_progress):
        if in_progress:
            return qs
        else:
            return qs.filter( accepted=self.request.user)

class View2( BaseView):
    template_name = 'temp2.html'

    def update_qs( self, qs, in_progress):
        if in_progress:
            return qs.filter( created = self.request.user)
        else:
            return qs.filter( created_by=self.request.user)