简体   繁体   English

Django CustomField从models.CharField继承-意外的关键字参数

[英]Django CustomField inheritance from models.CharField — unexpected keyword argument

My application needs few attributes that are required for the fields, so I went and followed the code to create custom fields . 我的应用程序需要字段所需要的一些属性,因此我继续按照代码创建了自定义字段

This is my CustomCharacterField: 这是我的CustomCharacterField:

class CustomCharField(models.CharField):
    def __int__(self, success_order=None, *args, **kwargs):
        self.success_order = success_order
        super(CustomCharField, self).__int__( *args, **kwargs)

    def get_success_order(self):
        return int(self.success_order)


    def deconstruct(self):
        name, path, args, kwargs = super(CustomCharField, self).deconstruct()
        del kwargs["success_order"]
        return name, path, args, kwargs

Here is my models.py 这是我的models.py

class NameModel(models.Model):

     name = fields.CustomCharField(max_length=250, unique=True, success_order=1)

Here is the traceback: 这是回溯:

 File "/home/kt/Documents/phc/phc/Forms/models.py", line 204, in <module>
   class SchemeModel(models.Model):
  File "/home/kt/Documents/phc/phc/Forms/models.py", line 220, in SchemeModel
    scheme_name = fields.CustomCharField(verbose_name="Scheme", max_length=250, unique=True, success_order=1)
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/__init__.py", line 1072, in __init__
    super(CharField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'success_order'

我认为您在这里只是一个错字def __int__应该是def __init__ ,而super(...).__int__(..)调用应该是super(...).__init__(..)

It is because of the order in which you pass the arguments. 这是因为您传递参数的顺序。 The trace back shows that success_order is being passed to the constructor of CharField, which should not be. 追溯显示成功订单已传递给CharField的构造函数,而不应该传递给CharField的构造函数。 This is because it is being passed in kwargs. 这是因为它在kwargs中传递。 Changing the order should do the trick. 更改顺序应该可以解决问题。 unique=True will be accepted by the CharField constructor. CharField构造函数将接受unique = True。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM