[英]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.