TypeError:super(type,obj):obj必须是类型的实例或子类型吗?

时间:2018-09-02 19:28:13

标签: django python-3.x django-models django-forms django-views

为什么会出现此错误?

TypeError: super(type, obj): obj must be an instance or subtype of type

这是我的models.py文件

class UserNotification(models.Model):
Name = models.CharField(max_length=250)
Mobile_No = models.CharField(max_length=10, validators=[RegexValidator(r'^\d{1,10}$')])
Proof = models.TextField()
viewed = models.BooleanField(default=False)
user = models.ForeignKey(User)
date = models.DateTimeField(default=timezone.now)

def __str__(self):
    return self.Name

class Meta:
    ordering = ["-date"]

这是我的views.py文件

class RequestItem(generic.CreateView):
    model = UserNotification
    fields = ['Name', 'Mobile_No', 'Proof']

    def get_form(self, form_class=None):
        if form_class is None:
            form_class = self.get_form_class()
        form = super(UserNotification, self).get_form(form_class)
        form.fields['Name'].widget = TextInput(attrs={'placeholder': '*Enter your name'})
        form.fields['Mobile_No'].widget = TextInput(
            attrs={'placeholder': "*Enter your's mobile number to get a call back from angel"})
        form.fields['Proof'].widget = TextInput(attrs={'placeholder': '*enter proof you have for your lost item'})
        return form

    def form_valid(self, form):
        print(self.kwargs)

        self.object = form.save(commit=False)
        qs = Report_item.objects.filter(id=self.kwargs.get("pk"))
        self.object.user = qs[0].owner
        self.object.save()
        return HttpResponse("<h1>Your request has been processed</h1>")

我正在使用Django 1.11。在添加占位符功能之前,没有错误,代码也无法正常工作。添加占位符后,出现此错误。请帮助我解决它。

1 个答案:

答案 0 :(得分:2)

问题是您在super()内部调用get_form。您需要使用当前类。由于某种原因,您将模型类放在了那里。它必须是:

form = super(RequestItem, self).get_form(form_class)

或者更好,因为您正在使用Python 3,所以请使用简短版本:

form = super().get_form(form_class)

但是请注意,这并不是执行您要在此处执行的操作的好方法。而是声明一个实际的表单类,该类为您要更改的字段设置窗口小部件属性,并通过在类级别设置form_class属性在视图类中引用它。