我如何在这里将两个模板视图合并到单个视图中?
Posted
技术标签:
【中文标题】我如何在这里将两个模板视图合并到单个视图中?【英文标题】:how do i combine two template views into on single view here? 【发布时间】:2022-01-03 14:08:56 【问题描述】:我已经实现了两个视图来根据choice_fields显示数据,但是我有两个视图,视图和模板中的逻辑略有不同,我如何将它们组合成一个以便我处理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_context_data 方法以返回不同的查询集,然后覆盖 get_template_names 方法以返回不同的模板 【参考方案1】:在基于类的视图中实现 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)
【讨论】:
以上是关于我如何在这里将两个模板视图合并到单个视图中?的主要内容,如果未能解决你的问题,请参考以下文章