[英]Different templates for UpdateView for the same model in Django
所以我有一个模板列出了用户购物车中的不同产品——我想让用户有机会从这个视图更新每个产品。 但根据产品类型,我想显示不同的“update_templates”。 这种情况的最佳方案应该是什么?
我应该为同一个 model 使用几个不同的 UpdateViews 吗? 喜欢:
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_tamplate_names
function。
class ProductUpdateView(UpdateView):
model = CartItem
fields = '__all__'
def get_template_names(self):
if(condition):
return '_product1_update_form'
else:
return '_product2_update_form'
您可以覆盖get_template_names()
function,如下所示:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.