Django中相同模型的UpdateView的不同模板



所以我有一个模板,在用户购物车中列出了不同的产品-我想让用户有机会从这个视图更新每个产品。但根据产品类型,我希望显示不同的"update_templates"。对于这种情况,最好的情况应该是什么?

我应该为同一个模型使用几个不同的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_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()

您应该覆盖get_tamplate_names函数。

class ProductUpdateView(UpdateView):
model = CartItem
fields = '__all__'
def get_template_names(self):
if(condition):
return '_product1_update_form'
else:
return '_product2_update_form'

看看类视图的流程-https://docs.djangoproject.com/en/2.2/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin.template_name

最新更新