Python Django中相同模型的UpdateView的不同模板
所以我有一个在用户购物车中列出不同产品的模板-我想让用户有机会从这个视图更新每个产品。但根据产品类型,我希望显示不同的“更新模板”。 对于这种情况,最好的方案是什么 我应该为同一个模型使用几个不同的UpdateView吗?比如:Python Django中相同模型的UpdateView的不同模板,python,django,django-views,Python,Django,Django Views,所以我有一个在用户购物车中列出不同产品的模板-我想让用户有机会从这个视图更新每个产品。但根据产品类型,我希望显示不同的“更新模板”。 对于这种情况,最好的方案是什么 我应该为同一个模型使用几个不同的UpdateView吗?比如: class ProductType1UpdateView(UpdateView): model = CartItem fields = '__all__' template_name_suffix = '_product1_update_form
class ProductType1UpdateView(UpdateView):
model = CartItem
fields = '__all__'
template_name_suffix = '_product1_update_form'
class ProductType2UpdateView(UpdateView):
model = CartItem
fields = '__all__'
template_name_suffix = '_product2_update_form'
或者我应该在一个视图中创建它,并添加一些if语句,根据产品类型显示适当的模板?比如:
class ProductUpdateView(UpdateView):
model = CartItem
fields = '__all__'
{here if statement checking product id}
template_name_suffix = '_product1_update_form'
{elif}
template_name_suffix = '_product2_update_form'
第一种选择是可行的,但我觉得不对。我将如何制定我的if声明以使用第二个选项。或者有其他更好的方法吗?您应该重写
get\u tamplate\u names
函数
class ProductUpdateView(UpdateView):
model = CartItem
fields = '__all__'
def get_template_names(self):
if(condition):
return '_product1_update_form'
else:
return '_product2_update_form'
查看类视图的流程-您可以覆盖函数,如下所示:
class ProductUpdateView(UpdateView):
model = CartItem
fields = '__all__'
def get_template_names(self):
if self.kwargs.get('id') == 1:
self.template_name_suffix = '_product1_update_form'
else:
self.template_name_suffix = '_product2_update_form'
return super(ProductUpdateView, self).get_template_names()