Python 覆盖Django';s模型选择场

Python 覆盖Django';s模型选择场,python,django,overriding,Python,Django,Overriding,因为我们需要我们的ModelChoiceField根据它们的使用位置具有不同的(非\uuuuuUnicode\uuuuuu)标签,所以我认为重写ModelChoiceField并使其接受一个额外的参数是一个明智的想法,该参数将被调用,而不是从\u实例中调用。我可以为我们需要的每一个实例创建一个子类,但这还不是很枯燥,是吗 我的新型号ChoiceField: import django.forms class ModelChoiceField(django.forms.ModelChoiceF

因为我们需要我们的ModelChoiceField根据它们的使用位置具有不同的(非
\uuuuuUnicode\uuuuuu
)标签,所以我认为重写ModelChoiceField并使其接受一个额外的参数是一个明智的想法,该参数将被调用,而不是从\u实例中调用。我可以为我们需要的每一个实例创建一个子类,但这还不是很枯燥,是吗

我的新型号ChoiceField:

import django.forms


class ModelChoiceField(django.forms.ModelChoiceField):
    """Subclasses Django's ModelChoiceField and adds one parameter, `obj_label`.
    This should be a callable with one argument (the current object) which
    returns a string to use as the label of that object or instance."""

    def __init__(self, obj_label=None, *args, **kwargs):
        super(django.forms.ModelChoiceField, self).__init__(*args, **kwargs)
        self.obj_label = obj_label

    def label_from_instance(self, obj):
        if self.obj_label:
            return self.label(obj)
        return super(django.forms.ModelChoiceField, self).label_from_instance(obj)
看起来很简单。我只对名为
obj_label
的参数感兴趣,并将其余的全部传递到modelcoocefield的
\uuuu init\uuuu
函数中。至少我是这么想的。Python现在抱怨
\uuuu init\uuuu
获取了意外的关键字参数。。。我这样称呼它:
national=modelcooicefield(queryset=Country.objects.all(),obj_label=lambda x:x.name(),empty_label=None)
,错误是:

Traceback:
File "/home/patrick/spng/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  103.                     resolver_match = resolver.resolve(request.path_info)
File "/home/patrick/spng/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
  321.                     sub_match = pattern.resolve(new_path)
File "/home/patrick/spng/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
  321.                     sub_match = pattern.resolve(new_path)
File "/home/patrick/spng/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
  223.             return ResolverMatch(self.callback, args, kwargs, self.name)
File "/home/patrick/spng/lib/python2.7/site-packages/django/core/urlresolvers.py" in callback
  230.         self._callback = get_callable(self._callback_str)
File "/home/patrick/spng/lib/python2.7/site-packages/django/utils/functional.py" in wrapper
  29.         result = func(*args)
File "/home/patrick/spng/lib/python2.7/site-packages/django/core/urlresolvers.py" in get_callable
  97.             mod = import_module(mod_name)
File "/home/patrick/spng/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
  35.     __import__(name)
File "/home/patrick/spng/src/internship/views.py" in <module>
  40. from resume.views import assemble_dict_list
File "/home/patrick/spng/src/resume/views.py" in <module>
  20. from resume.forms import (HobbyForm, LanguageForm, EducationForm,
File "/home/patrick/spng/src/resume/forms.py" in <module>
  29. class NationalityForm(forms.ModelForm):
File "/home/patrick/spng/src/resume/forms.py" in NationalityForm
  31.     nationality = ModelChoiceField(queryset=Country.objects.all(), obj_label=lambda x: x.nationality(), empty_label=None)
File "/home/patrick/spng/src/stageplaza_ng/fields.py" in __init__
  11.         super(django.forms.ModelChoiceField, self).__init__(*args, **kwargs)
File "/home/patrick/spng/lib/python2.7/site-packages/django/forms/fields.py" in __init__
  672.                                         initial=initial, help_text=help_text, *args, **kwargs)

Exception Type: TypeError at /stagiaires/overzicht/
Exception Value: __init__() got an unexpected keyword argument 'queryset'
回溯:
get_响应中的文件“/home/patrick/spng/lib/python2.7/site packages/django/core/handlers/base.py”
103解析程序匹配=解析程序.resolve(请求.path\u信息)
解析中的文件“/home/patrick/spng/lib/python2.7/site packages/django/core/urlresolvers.py”
321子匹配=模式解析(新路径)
解析中的文件“/home/patrick/spng/lib/python2.7/site packages/django/core/urlresolvers.py”
321子匹配=模式解析(新路径)
解析中的文件“/home/patrick/spng/lib/python2.7/site packages/django/core/urlresolvers.py”
223返回ResolverMatch(self.callback、args、kwargs、self.name)
回调中的文件“/home/patrick/spng/lib/python2.7/site packages/django/core/urlresolvers.py”
230self.\u callback=get\u callable(self.\u callback\u str)
包装器中的文件“/home/patrick/spng/lib/python2.7/site packages/django/utils/functional.py”
29结果=func(*args)
get_callable中的文件“/home/patrick/spng/lib/python2.7/site packages/django/core/urlresolvers.py”
97mod=导入模块(mod\u名称)
导入模块中的文件“/home/patrick/spng/lib/python2.7/site packages/django/utils/importlib.py”
35.     __导入(名称)
文件“/home/patrick/spng/src/实习生/views.py”
40从resume.views导入汇编目录列表
文件“/home/patrick/spng/src/resume/views.py”
20从resume.forms导入(HobbyForm、LanguageForm、EducationForm、,
文件“/home/patrick/spng/src/resume/forms.py”
29.类别国家表格(forms.ModelForm):
NationalityForm中的文件“/home/patrick/spng/src/resume/forms.py”
31.国籍=modelcooicefield(queryset=Country.objects.all(),obj_label=lambda x:x.national(),空_label=None)
init中的文件“/home/patrick/spng/src/stageplaza_ng/fields.py”__
11.super(django.forms.modelcoocefield,self)。\uuuuu init\uuuuuu(*args,**kwargs)
init中的文件“/home/patrick/spng/lib/python2.7/site packages/django/forms/fields.py”__
672.首字母=首字母,帮助文本=帮助文本,*args,**kwargs)
异常类型:位于/stagiaires/overzicht的TypeError/
异常值:\uuuu init\uuuuu()获取了意外的关键字参数“queryset”

这可能是非常愚蠢的事情,那么有人有什么想法吗?

将您的类重命名为ModelChoiceField以外的类,请注意剩余的逻辑

 class CustomModelChoiceField(django.forms.ModelChoiceField):
        """Subclasses Django's ModelChoiceField and adds one parameter, `obj_label`.
        This should be a callable with one argument (the current object) which
        returns a string to use as the label of that object or instance."""

        def __init__(self, obj_label=None, *args, **kwargs):
            super(CustomModelChoiceField, self).__init__(*args, **kwargs)
            self.obj_label = obj_label

        def label_from_instance(self, obj):
            if self.obj_label:
                return self.label(obj)
            return super(CustomModelChoiceField, self).label_from_instance(obj)

重命名ModelChoiceField以外的类,请注意剩余的逻辑

 class CustomModelChoiceField(django.forms.ModelChoiceField):
        """Subclasses Django's ModelChoiceField and adds one parameter, `obj_label`.
        This should be a callable with one argument (the current object) which
        returns a string to use as the label of that object or instance."""

        def __init__(self, obj_label=None, *args, **kwargs):
            super(CustomModelChoiceField, self).__init__(*args, **kwargs)
            self.obj_label = obj_label

        def label_from_instance(self, obj):
            if self.obj_label:
                return self.label(obj)
            return super(CustomModelChoiceField, self).label_from_instance(obj)

事实证明这真的很愚蠢。我在超级呼叫中呼叫Django ModelChoiceField super。这样:
super(django.forms.modelcoocefield,self)。\uuu init\uu(*args,**kwargs)
。在这种情况下,我得到这个异常是非常合理的。模型ChoiceField super就是ChoiceField。并且该类不接受名为
queryset
的关键字参数

事实上,我应该打电话给本班的超级老师。像这样:
super(modelcoocefield,self)。\uuu init\uuu(*args,**kwargs)
。这在文档中出现过很多次,但这次我有点错过了。ModelChoiceField的正确覆盖为:

import django.forms


class ModelChoiceField(django.forms.ModelChoiceField):
    """Subclasses Django's ModelChoiceField and adds one parameter, `obj_label`.
    This should be a callable with one argument (the current object) which
    returns a string to use as the label of that object or instance."""

    def __init__(self, obj_label=None, *args, **kwargs):
        super(ModelChoiceField, self).__init__(*args, **kwargs)
        self.obj_label = obj_label

    def label_from_instance(self, obj):
        if self.obj_label:
            return self.label(obj)
        return super(ModelChoiceField, self).label_from_instance(obj)

这很有效。但我必须部分同意斯里尼瓦斯的回答。更名为ModelChoiceField更为清晰,因此可以立即清楚地知道发生了什么。

事实证明,这确实是件愚蠢的事情。我在超级呼叫中呼叫Django ModelChoiceField super。这样:
super(django.forms.modelcoocefield,self)。\uuu init\uu(*args,**kwargs)
。在这种情况下,我得到这个异常是非常合理的。模型ChoiceField super就是ChoiceField。并且该类不接受名为
queryset
的关键字参数

事实上,我应该打电话给本班的超级老师。像这样:
super(modelcoocefield,self)。\uuu init\uuu(*args,**kwargs)
。这在文档中出现过很多次,但这次我有点错过了。ModelChoiceField的正确覆盖为:

import django.forms


class ModelChoiceField(django.forms.ModelChoiceField):
    """Subclasses Django's ModelChoiceField and adds one parameter, `obj_label`.
    This should be a callable with one argument (the current object) which
    returns a string to use as the label of that object or instance."""

    def __init__(self, obj_label=None, *args, **kwargs):
        super(ModelChoiceField, self).__init__(*args, **kwargs)
        self.obj_label = obj_label

    def label_from_instance(self, obj):
        if self.obj_label:
            return self.label(obj)
        return super(ModelChoiceField, self).label_from_instance(obj)

这很有效。但我必须部分同意斯里尼瓦斯的回答。重命名为ModelChoiceField更为清晰,因此可以立即清楚发生了什么。

重命名您的类而不是
ModelChoiceField
重命名您的类而不是
ModelChoiceField
除了重命名此项,您还修复了问题:)我在超级调用中使用了错误的模型…您在哪里实现此功能?是什么?这对于获取绑定到外键的模型并拆分用户的显示字段有用吗?除了重命名此项,您还修复了问题:)我在超级调用中使用了错误的模型…您在哪里实现此功能?是什么?这对于获取绑定到外键的模型以及为用户拆分显示字段是否有用?