python - 覆盖 Django 的 ModelChoiceField

标签 python django overriding

因为我们需要我们的 ModelChoiceFields 根据它们的使用位置具有不同的(非 __unicode__)标签,我认为覆盖 ModelChoiceField 并让它接受一个额外的是一个聪明的主意将被调用而不是 label_from_instance 的参数。我本可以为我们需要的每个实例创建一个子类,但这并不是真正的 DRY,是吗?

我的新 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(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 的参数感兴趣,并将所有其他参数传递给 ModelChoiceField 的 __init__ 函数。或者我是这么想的。 Python 现在提示 __init__ 得到意想不到的关键字参数......我这样调用它:nationality = ModelChoiceField(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'

这可能真的很愚蠢,所以有人有想法吗?

最佳答案

重命名你的类而不是 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)

关于python - 覆盖 Django 的 ModelChoiceField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18592785/

相关文章:

python - 每隔一行用特殊条件用 0 替换空值

python - Django 如果 user.is_authenticated 不工作

django-cacheops 与 aws redis 加密

objective-c - 如何在 Swift 中覆盖 Objective-c 类函数?

c# - 为什么我在覆盖和调用虚函数时没有得到 stackoverflow 异常?

python - 使用 python 和 bs4 进行网页抓取

python - 覆盖Python中的内置函数

Django 翻译 : add custom translation

java - 如何覆盖 Jar 中定义的资源文件?

python - 告诉 Django Compressor 在编译时忽略某些目录