【问题标题】:Different templates for UpdateView for the same model in DjangoDjango中同一模型的UpdateView的不同模板
【发布时间】:2019-10-24 12:12:32
【问题描述】:

所以我有一个模板列出了用户购物车中的不同产品 - 我想让用户有机会从这个视图更新每个产品。但根据产品类型,我想显示不同的“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 语句以使用第二个选项。或者还有其他更好的方法吗?

【问题讨论】:

    标签: python django django-views


    【解决方案1】:

    你可以重写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()
    

    【讨论】:

      【解决方案2】:

      你应该重写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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-07
        • 1970-01-01
        • 2014-04-11
        • 1970-01-01
        • 1970-01-01
        • 2021-11-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多