【问题标题】:class based views -TypeError: super(type, obj): obj must be an instance or subtype of type基于类的视图 -TypeError: super(type, obj): obj must be an instance or subtype of type
【发布时间】:2021-04-14 15:09:00
【问题描述】:

我正在 Django 中构建一个应用程序,它使用基于类的视图。

在我的views.py中,我有这个基于类的视图,允许检查我的模型Product中对象的细节:

class ProductDetailView(DetailView):
    queryset = Product.objects.all()
    template_name = "products/detail.html"

    def get_context_data(self, *args, **kwargs):
        context = super(ProductListView, self).get_context_data(*args, **kwargs)
        return context

当我尝试运行服务器时,我得到了这个回溯:

Traceback (most recent call last):
...
context = super(ProductListView, self).get_context_data(*args, **kwargs)
TypeError: super(type, obj): obj must be an instance or subtype of type

有什么问题?

【问题讨论】:

    标签: python django super django-class-based-views


    【解决方案1】:

    当你自己推导出来时,类型应该是selfMethod Resolution Order (MRO) 的一个元素,所以:

    class ProductDetailView(DetailView):
        queryset = Product.objects.all()
        template_name = 'products/detail.html'
    
        def get_context_data(self, *args, **kwargs):
            context = super(ProductDetailView, self).get_context_data(*args, **kwargs)
            return context

    然而,由于,你确实不需要需要将参数传递给super():如果你使用定义它的类,并且self作为参数,你可以使用super(),因此您可以将其重写为:

    class ProductDetailView(DetailView):
        queryset = Product.objects.all()
        template_name = 'products/detail.html'
    
        def get_context_data(self, *args, **kwargs):
            context = super().get_context_data(*args, **kwargs)
            return context

    因此,这使得定义可以轻松复制粘贴到其他视图的代码片段变得容易。

    而且这里重写get_context_data是没有意义的,因为你只调用了super方法并返回了它的结果,你可以省略重写。

    【讨论】:

      【解决方案2】:

      已解决

      回溯说

      obj 必须是类型的实例或子类型

      指向super(type, obj)

      这意味着您传递给 super 的第二个参数必须是第一个参数的实例或子类型。

      如果您查看您的代码,ProductListView 不是self 的实例或子类型,在这种情况下等于ProductDetailView

      这显然是一个糟糕的复制粘贴问题。替换

      context = super(ProductListView, self).get_context_data(*args, **kwargs)
      

      context = super(ProductDetailView, self).get_context_data(*args, **kwargs)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-05
        • 2014-08-29
        • 2021-05-12
        • 2021-11-23
        • 2017-08-14
        • 2018-03-31
        • 1970-01-01
        相关资源
        最近更新 更多