簡體   English   中英

Python 3 中的 Django 問題“super() 參數 1 必須是類型,而不是 WSGIRequest”

[英]Django problem "super() argument 1 must be type, not WSGIRequest" in Python 3

雖然要使用類繼承,但 Python 3 失敗, super() argument 1 must be type, not WSGIRequest

我在 Django 2.1.4 和 Python 3.7.0 上。 我正在嘗試查看用戶是否已經提交了要分析的文件,如果沒有,則將其定向到提交頁面。 我試圖不使用靜態方法,檢查它是否真的是 Python 3(因為這個問題在 Python 2 上很常見),在我嘗試從“對象”繼承的超類上,同時也從 Django 提供的“視圖”繼承(因為這在 Python 2 super() 中解決了參數 1 must be type 而不是 None )。

這是超類,它繼承自Django“View”提供的類。

class DatasetRequired(View):

    @staticmethod
    def get(request):
        <redirects the user>

這是基類

class Estatisticas(DatasetRequired):

    @staticmethod
    def get(request):
        super(request)
        <do various other stuff>

我期望基類的get函數在調用時會調用超類get函數並檢查用戶是否已經提交了文件。

我得到:

TypeError at /estatisticas super() argument 1 must be type, not WSGIRequest

您誤解了如何使用super() 您將傳入當前類和第二個參數的實例或類,而不是request對象。 該調用的結果是一個特殊的對象,它知道如何通過忽略當前類來查找和綁定父類上的屬性。

staticmethod上下文中,您必須將當前類作為兩個參數傳入:

class Estatisticas(DatasetRequired):
    @staticmethod
    def get(request):
        super(Estatisticas, Estatisticas).get(request)
        # <do various other stuff>

我真的不知道你為什么在這里使用staticmethod 處理請求時,會為視圖創建一個特殊實例,因此您通常使用普通實例方法 此時,在 Python 3 中,您可以使用不帶參數的super()

class DatasetRequired(View):

    def get(self, request):
        # <redirects the user>

class Estatisticas(DatasetRequired):

    def get(self, request):
        super().get(request)
        # <do various other stuff>

Python 有足夠的上下文來知道super()需要Estatisticasself作為參數,而無需您命名它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM