Как объединить два представления шаблона в одно представление?
Я реализовал два представления для отображения данных в соответствии с полями выбора, но у меня есть два представления с немного разной логикой в представлениях и шаблонах, как мне объединить их в одно, чтобы я позаботился о 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
Воспользуйтесь чем-то вроде get_queryset
в представлениях на основе классов.
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)