![](/img/trans.png)
[英]Python - TypeError: super(type, obj): obj must be an instance or subtype of type?
[英]class based views -TypeError: super(type, obj): obj must be an instance or subtype of type
我正在 Django 中構建一個應用程序,它使用基於 class 的視圖。
在我的 views.py 中,我有這個基於 class 的視圖,允許檢查我的 model 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
問題是什么?
當您自己派生時,該類型應該是self
的 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
但是,由於python-3.x ,您不需要將參數傳遞給super()
:如果您使用定義它的 class 和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 方法並返回其結果,您可以省略重寫。
解決了
回溯說
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.