因此,我在用户购物车中有一个列出不同产品的模板-我想让用户有机会从该视图更新每个产品。但是根据产品类型,我想显示不同的“ update_templates”。在这种情况下最好的方案是什么?
我应该为同一模型使用几个不同的UpdateView吗?喜欢:
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_template_names()
函数,如下所示:
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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句