我在一个小的Django应用程序上工作,得到一个错误,告诉我,super(type, obj): obj must be an instance or subtype of type.在引入函数get_object_or_404之后,我从views.py文件中获得了它.下面提供的views.py文件,

from django.shortcuts import render, get_object_or_404    
from django.http import HttpResponse, HttpResponseRedirect     
from django.views import View     
from .models import URL


# function based view 
def redirect_view(request, shortcode=None, *args, **kwargs):
    obj = get_object_or_404(URL, shortcode=shortcode)
    return HttpResponse("Hello World, the shortcode is {shortcode}".format(shortcode = obj.url))


# class based view 
class ShortenerView(View):

    def get(self, request, shortcode=None,  *args, **kwargs):
        obj = get_object_or_404(URL, shortcode=shortcode)
        return HttpResponse("Hello World 1, the shortcode is {shortcode}".format(shortcode = obj.url))

    def post(self, request, *args, **kwargs):
        return HttpResponse()

完整的错误消息在此,

TypeError at /b/p6jzbp/
super(type, obj): obj must be an instance or subtype of type
Request Method: GET
Request URL:    http://127.0.0.1:8000/b/p6jzbp/
Django Version: 1.11
Exception Type: TypeError
Exception Value:    
super(type, obj): obj must be an instance or subtype of type
Exception Location: /Users/Chaklader/Documents/Projects/UrlShortener/src/shortener/models.py in all, line 18

models.py中的line 18qs_main = super(URL, self).all(*args, **kwargs),models.py文件在这里,

#  will look for the "SHORTCODE_MAX" in the settings and 
#  if not found, will put the value of 15 there 
SHORTCODE_MAX = getattr(settings, "SHORTCODE_MAX", 15)



class UrlManager(models.Manager):

    def all(self, *args, **kwargs):
        qs_main = super(URL, self).all(*args, **kwargs)
        qs      = qs_main.filter(active = True)
        return qs

    def refresh_shortcodes(self, items = None):

        qs = URL.objects.filter(id__gte=1)
        new_codes = 0

        if items is not None and isinstance(items, int):
            qs = qs.order_by('-id')[:items]

        for q in qs:
            q.shortcode = create_shortcode(q)
            print (q.id, " ", q.shortcode)
            q.save()
            new_codes += 1

        return "# new codes created {id}".format(id = new_codes)


class URL(models.Model):

    url         =  models.CharField(max_length = 220, )
    shortcode   =  models.CharField(max_length = SHORTCODE_MAX, blank = True, unique = True)
    updated     =  models.DateTimeField(auto_now = True)
    timestamp   =  models.DateTimeField(auto_now_add = True)
    active      = models.BooleanField(default = True)

    objects = UrlManager()

    def save(self, *args, **kwargs):

        if self.shortcode is  None or self.shortcode == "":
            self.shortcode = create_shortcode(self)

        super(URL, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.url)

    def __unicode__(self):
        return str(self.url)

    # class Meta:
    #   ordering = '-id'

有没有人能给我解释一下出错的原因和如何解决?如果需要,我愿意提供更多信息.

推荐答案

您应该使用UrlManager类作为第一个参数来调用super,而不是使用URL模型.不能使用unrelated类/类型调用super BE:

从文件上看,

super(type[, object-or-type]): 返回将方法调用委托给父级的代理对象或 类型的sibling 类.

所以你们cannot人要做:

>>> class D:
...    pass
... 
>>> class C:
...    def __init__(self):
...        super(D, self).__init__()
... 
>>> C()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
TypeError: super(type, obj): obj must be an instance or subtype of type

您应该执行以下操作:

qs_main = super(UrlManager, self).all(*args, **kwargs)

或者在Python 3中:

qs_main = super().all(*args, **kwargs)

Django相关问答推荐

Django后端对印前判断请求未通过访问控制判断给我以下回应:否访问控制允许来源

Django测试:如何模拟Django_apps.get_Model()的LookupError

Django modelform在包含在另一个模板中时不呈现

如何在Django中显示文件大小

CsrfViewMiddleware 和 enforce_csrf 有什么区别?

过滤查询以获取两个朋友之间的聊天消息?

为什么在 Docker 映像中运行我的 Django 应用程序后下载属性不再起作用?

Django获取具有值的相关对象的计数并将其添加到注释中

如何在 Django 中创建一个独特的 slug

是否可以在没有模型的情况下创建自定义管理视图

AttributeError:'Manager'对象在Django中没有属性'get_by_natural_key'错误?

InvalidBasesError:无法解析 [] 的基础

有没有办法将变量传递给 Django 中的 extended模板?

(fields.E300) 字段定义与模型的关系,该模型要么未安装,要么是抽象的

AngularJS + Django Rest Framework + CORS(CSRF Coo​​kie 没有出现在客户端)

如何使用 django-nose 运行单个测试或单个 TestCase?

django过滤器超过几天?

如何获取经过身份验证的用户列表?

过滤查询参数

提供来自 django 的压缩内容