简体   繁体   中英

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:

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

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. This is because it is being passed in kwargs. Changing the order should do the trick. unique=True will be accepted by the CharField constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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