python - Python 3 中的 Django 问题 "super() argument 1 must be type, not WSGIRequest"

标签 python django python-3.x super

当使用类继承时,Python 3 失败,super() argument 1 must be type, not WSGIRequest

我使用的是 Django 2.1.4 和 Python 3.7.0。我试图查看用户是否已经提交了要分析的文件,如果没有,他将被定向到提交页面。我试图不使用静态方法,检查它是否真的是 Python 3(因为这个问题在 Python 2 上很常见),在我试图从“对象”继承的父类(super class)上,同时也从 Django 提供的“ View ”继承(因为这在 Python 2 中解决了 super() argument 1 must be type, not None)。

这是父类(super class),它继承自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 函数在被调用时会调用父类(super class)的 get 函数并检查用户是否已经提交了文件。

我得到:

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

最佳答案

你误解了如何使用 super()。您将传入当前类和第二个参数的实例或类,而不是 request 对象。该调用的结果是一个特殊对象,它知道如何通过忽略当前类来查找和绑定(bind)父类的属性。

staticmethod 上下文中,您必须将当前类作为两个参数传递:

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

我真的不确定你为什么在这里使用 staticmethod。处理请求时,会为 View 创建一个特殊实例,因此您通常使用普通实例方法。此时,在 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 作为参数,而您不必为它们命名。

关于python - Python 3 中的 Django 问题 "super() argument 1 must be type, not WSGIRequest",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54268065/

相关文章:

django - 在 Django 中获取原始请求 header

python - Django 4.04 中具有区域设置感知功能的正确工作千位分隔符

python - 为什么我不能从导入的模块中调用 globals()?

python - 使用 django FORM 上传文件的唯一文件名

python - 导入 pymorphy2 时出现异常

python - 如何编辑 RedirectView 的 kwargs?

python - ValueError : Invalid value for selector, 不能为 None

python - 将信息存储到.exe文件中,从python导出

css - 香脆形式 : add css class for one of the inputs

python - 提交按钮在 python 3 中无法正常工作。怎么解决?