代码之家  ›  专栏  ›  技术社区  ›  fabio

AttributeError:模型对象没有属性“rel”

  •  1
  • fabio  · 技术社区  · 7 年前

    在django 1.9中,我使用了这个自定义的多语言charfield,然后我升级到django 2.0,它在runserver上给出了错误:

    class MultilingualCharField(models.CharField):
    
        def __init__(self, verbose_name=None, **kwargs):
            self._blank = kwargs.get("blank", False)
            self._editable = kwargs.get("editable", True)
            #super(MultilingualCharField, self).__init__(verbose_name, **kwargs)
            super().__init__(verbose_name, **kwargs)
    
        def contribute_to_class(self, cls, name, virtual_only=False):
            # generate language specific fields dynamically
            if not cls._meta.abstract:
                for lang_code, lang_name in settings.LANGUAGES:
                    if lang_code == settings.LANGUAGE_CODE:
                        _blank = self._blank
                    else:
                        _blank = True
                    localized_field = models.CharField(string_concat(
                        self.verbose_name, " (%s)" % lang_code),
                        name=self.name,
                        primary_key=self.primary_key,
                        max_length=self.max_length,
                        unique=self.unique,
                        blank=_blank,
                        null=False,
                        # we ignore the null argument!
                        db_index=self.db_index,
                        rel=self.rel,
                        default=self.default or "",
                        editable=self._editable,
                        serialize=self.serialize,
                        choices=self.choices,
                        help_text=self.help_text,
                        db_column=None,
                        db_tablespace=self.db_tablespace
                    )
                    localized_field.contribute_to_class(cls, 
                        "%s_%s" % (name, lang_code),)
    
            def translated_value(self):
                language = get_language()
                val = self.__dict__["%s_%s" % (name, language)]
                if not val:
                    val = self.__dict__["%s_%s" % (name, settings.LANGUAGE_CODE)]
                    return val
    
            setattr(cls, name, property(translated_value))
    
        def name(self):
            name_translated='name'+settings.LANGUAGE_CODE
            return name_translated
    

    错误如下:

    (possedimenti) D:\Python\progetti\possedimenti\sitopossedimenti>manage.py runserver
    Unhandled exception in thread started by <function check_errors.<locals>.wrapper
     at 0x03BCB8E8>
    Traceback (most recent call last):
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py
    ", line 225, in wrapper
        fn(*args, **kwargs)
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\core\management\com
    mands\runserver.py", line 112, in inner_run
        autoreload.raise_last_exception()
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py
    ", line 248, in raise_last_exception
        raise _exception[1]
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\core\management\__i
    nit__.py", line 327, in execute
        autoreload.check_errors(django.setup)()
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py
    ", line 225, in wrapper
        fn(*args, **kwargs)
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\__init__.py", line
    24, in setup
        apps.populate(settings.INSTALLED_APPS)
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\apps\registry.py",
    line 112, in populate
        app_config.import_models()
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\apps\config.py", li
    ne 198, in import_models
        self.models_module = import_module(models_module_name)
      File "D:\python\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 986, in _gcd_import
      File "<frozen importlib._bootstrap>", line 969, in _find_and_load
      File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 665, in exec_module
      File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
      File "D:\Python\progetti\possedimenti\sitopossedimenti\core\models\__init__.py
    ", line 1, in <module>
        from core.models.campaign import Source, Ability
      File "D:\Python\progetti\possedimenti\sitopossedimenti\core\models\campaign.py
    ", line 6, in <module>
        class Ability(models.Model):
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\db\models\base.py",
     line 152, in __new__
        new_class.add_to_class(obj_name, obj)
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\db\models\base.py",
     line 315, in add_to_class
        value.contribute_to_class(cls, name)
      File "D:\Python\progetti\possedimenti\sitopossedimenti\sitopossedimenti\utils.
    py", line 45, in contribute_to_class
        rel=self.rel,
    AttributeError: 'MultilingualCharField' object has no attribute 'rel'
    

    也许在django 2.0中,该属性不再存在了?我不知道它是什么,我需要什么。谢谢你的帮助。如果我把这句话注释掉,它看起来是有效的。。。但我不确定它将来会做什么。。。

    编辑:

    所以,是的 deprecated (同时 here ),有人知道我该怎么做吗?我试着换线 contribute_to_class (见上文)在:

    ...
    #rel=self.rel,
    remote_field=self.remote_field,
    ...
    

    但它给出了一个错误 .../models/__init__.py :

    TypeError: __init__() got an unexpected keyword argument 'remote_field'
    

    完整回溯:

    Unhandled exception in thread started by <function check_errors.<locals>.wrapper
     at 0x03BF0108>
    Traceback (most recent call last):
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py
    ", line 225, in wrapper
        fn(*args, **kwargs)
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\core\management\com
    mands\runserver.py", line 112, in inner_run
        autoreload.raise_last_exception()
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py
    ", line 248, in raise_last_exception
        raise _exception[1]
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\core\management\__i
    nit__.py", line 327, in execute
        autoreload.check_errors(django.setup)()
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py
    ", line 225, in wrapper
        fn(*args, **kwargs)
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\__init__.py", line
    24, in setup
        apps.populate(settings.INSTALLED_APPS)
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\apps\registry.py",
    line 112, in populate
        app_config.import_models()
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\apps\config.py", li
    ne 198, in import_models
        self.models_module = import_module(models_module_name)
      File "D:\python\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 986, in _gcd_import
      File "<frozen importlib._bootstrap>", line 969, in _find_and_load
      File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 665, in exec_module
      File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
      File "D:\Python\progetti\possedimenti\sitopossedimenti\core\models\__init__.py
    ", line 1, in <module>
        from core.models.campaign import Source, Ability
      File "D:\Python\progetti\possedimenti\sitopossedimenti\core\models\campaign.py
    ", line 6, in <module>
        class Ability(models.Model):
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\db\models\base.py",
     line 152, in __new__
        new_class.add_to_class(obj_name, obj)
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\db\models\base.py",
     line 315, in add_to_class
        value.contribute_to_class(cls, name)
      File "D:\Python\progetti\possedimenti\sitopossedimenti\sitopossedimenti\utils.
    py", line 53, in contribute_to_class
        db_tablespace=self.db_tablespace
      File "D:\Python\Envs\possedimenti\lib\site-packages\django\db\models\fields\__
    init__.py", line 1042, in __init__
        super().__init__(*args, **kwargs)
    TypeError: __init__() got an unexpected keyword argument 'remote_field'
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Oliver Falk    7 年前

    我最终遇到了类似或相关的问题:

    File "XXX/.virtualenv/lib/python3.4/site-packages/natural_keys/models.py", line 168, in natural_key
      for name in self.get_natural_key_fields()]
    File "XXX/.virtualenv/lib/python3.4/site-packages/natural_keys/models.py", line 149, in get_natural_key_fields
      for name, rel_to in cls.get_natural_key_info():
    File "XXX/.virtualenv/lib/python3.4/site-packages/natural_keys/models.py", line 129, in get_natural_key_info
      rel_to = field.rel.to if field.rel else None
    AttributeError: 'CharField' object has no attribute 'rel'
    

    不确定这是否有助于解决问题。

    推荐文章