TypeError:__init __()缺少1个必需的位置参数:'on_delete'(Django 2)

时间:2019-09-14 23:47:09

标签: python django python-3.x django-filer

我需要在以下代码中添加所需的参数:on_delete = models.CASCADE。否则,我得到以下内容

TypeError: __init__() missing 1 required positional argument: 'on_delete'.

我应该如何在哪里进行?

class FilerFileField(models.ForeignKey):
    default_form_class = AdminFileFormField
    default_model_class = File 

    def __init__(self, **kwargs):
        # We hard-code the `to` argument for ForeignKey.__init__
        dfl = get_model_label(self.default_model_class)
        if "to" in kwargs.keys():  # pragma: no cover
            old_to = get_model_label(kwargs.pop("to"))
            if old_to != dfl:
                msg = "%s can only be a ForeignKey to %s; %s passed" % (
                    self.__class__.__name__, dfl, old_to
                )
                warnings.warn(msg, SyntaxWarning)
        kwargs['to'] = dfl
        super(FilerFileField, self).__init__(**kwargs)

    def formfield(self, **kwargs):
        # This is a fairly standard way to set up some defaults
        # while letting the caller override them.
        defaults = {
            'form_class': self.default_form_class,
        }
        try:
            defaults['rel'] = self.remote_field
        except AttributeError:
            defaults['rel'] = self.rel
        defaults.update(kwargs)
        return super(FilerFileField, self).formfield(**defaults)

2 个答案:

答案 0 :(得分:2)

它将位于super(FilerFileField, self).__init__(**kwargs)函数的最后一行__init__中。

您会看到on_deleteForeignKey类的必需参数。 https://docs.djangoproject.com/en/2.2/ref/models/fields/#foreignkey https://docs.djangoproject.com/en/2.2/ref/models/fields/#arguments

类似于super(FilerFileField, self).__init__(on_delete=models.CASCADE, **kwargs)的事情。

答案 1 :(得分:0)

当你使用任何像 FK 这样的 Filer 模型时,你需要添加 on_delete=models.CASCADE