Django update或create obj必须是typ的实例或子类型

2024-09-29 06:26:29 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的表单有效函数中有一个update或create方法,当我提交表单时,我得到了错误。我不知道为什么?在

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

完整跟踪:

^{pr2}$

这是视图中的函数

if request.method == 'GET':
    form = DeviceSubnetForm()
else:
    # A POST request: Handle Form Upload
    form = DeviceSubnetForm(request.POST)
    # If data is valid, proceeds to create a new post and redirect the user
    if form.is_valid():
        subnet_data = form.save(commit=False)
        obj, record = DeviceSubnet.objects.update_or_create(
            defaults={
                'subnet' : subnet_data.subnet,
                'subnet_mask'  : subnet_data.subnet_mask,
                'subnet_type' : SubnetTypes.objects.get(subnet_data.subnet_type)
                },
            subnet=subnet_data.subnet,
            subnet_mask=subnet_data.subnet_mask,
            subnet_type=SubnetTypes.objects.get(subnet_data.subnet_type)
        )
        print(obj.id)
        return 'Valid'

在表单.py在

class DeviceSubnetForm(forms.ModelForm):
    class Meta:
        model = DeviceSubnet
        fields = ['subnet', 'subnet_mask','subnet_type',]

    def __init__(self, *args, **kwargs):
        super(DeviceSubnet, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

Tags: selfformobj表单dataobjectsrequesttype
1条回答
网友
1楼 · 发布于 2024-09-29 06:26:29

由于此代码super(DeviceSubnet, self).__init__(*args, **kwargs)位于DeviceSubnetForm内,您应该将super方法的第一个参数替换为DeviceSubnetForm类:

super(DeviceSubnetForm, self).__init__(*args, **kwargs)

或者使用python3可以跳过参数:

^{pr2}$

相关问题 更多 >