Django - 更新或创建obj必须是类型的实例或子类型

时间:2018-03-13 17:44:28

标签: python django

我提交表单时,我的表单有效函数中有更新或创建方法,我得到错误。我不确定为什么?

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

完整追踪:

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/itapp/itapp/config/views.py" in device_details
  151.         form = DeviceSubnetForm(request.POST)

File "/itapp/itapp/config/forms.py" in __init__
  135.         super(DeviceSubnet, self).__init__(*args, **kwargs)

Exception Type: TypeError at /config/device_details/2/7
Exception Value: super(type, obj): obj must be an instance or subtype of type

这是视图中的功能

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'

forms.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'

1 个答案:

答案 0 :(得分:4)

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

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

或使用python3跳过参数:

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