So I've got a template listing different products in user cart - I would like to give user a chance to update each product from this view. But depending on product type I would like to display different 'update_templates'. What should be the best scenario for this situation?
Should I use few different UpdateViews for the same model? Like:
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'
Or should I make it in one view, and add some if statements that will display proper template depending on product type? Like:
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'
The first option works, but it doesn't feel right to me. How would I formulate my if statement to make it with the second option. Or is there maye another, better way to do it?
You should override 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'
Look at the flow of class view - https://docs.djangoproject.com/en/2.2/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin.template_name
You can override get_template_names()
function, like this:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.