繁体   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