【发布时间】:2020-06-13 02:34:37
【问题描述】:
我将 Django Forms 用于我的 Web 应用程序的前端过滤器功能,并且我正在进行一些字段自定义,以便我可以显示带有自定义标签的多选复选框,如下所示:
[x] 道格搞笑 (1)
[ ] 斯基特瓦伦丁(5)
[x] 帕蒂蛋黄酱(3)
[ ] 罗杰·克洛茨 (9)
选择一个选项后,我可以通过覆盖我的表单 init 方法来动态更新复选框字段标签(特别是计数),如下所示:
class FiltersForm(forms.Form):
...
studentCheckbox = MyModelMultipleChoiceField(widget=MyMultiSelectWidget, queryset=Student.objects.all(), required=False)
...
def __init__(self, *args, **kwargs):
super(FiltersForm, self).__init__(*args, **kwargs)
students = Student.objects.values(...).annotate(count=Count(...))
self.fields['studentCheckbox'].queryset = Student.objects.all()
# dynamically updating the field's label here to include a count
self.fields['studentCheckbox'].label_from_instance = lambda obj: "%s (%s)" % (students.get(pk=obj.pk)['name'], students.get(pk=obj.pk)['count'])
但不是“硬编码”字段标签中的计数,我想动态地将计数设置为每个小部件选项字段的“数据计数”属性。在我尝试这样做时,我将forms.ModelMultipleChoiceField 子类化为MyModelMultipleChoiceField。
我希望重写MyModelMultipleChoiceField中的label_from_instance函数来动态访问obj(通过pk)并在过程中设置data-count属性。然而,出于某种原因,我的表单的 init (self.fields['studentCheckbox'].label_from_instance) 中的 lambda 调用并未调用 label_from_instance 函数。我还尝试在表单和自定义小部件 (MyMultiSelectWidget) 上覆盖 label_from_instance 函数,但无济于事。
class MyModelMultipleChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, obj):
print(obj) # nothing prints
if hasattr(obj, 'count'):
self.widget.attrs.update({obj.pk: {'data-count': obj.count}})
return obj
# I probably don't need to subclass the Widget, but just in case...
# I originally thought I could do something with create_option(count=None), but I need access to the
# obj, as I can't use a lambda with self.fields['studentCheckbox'].widget.count = lambda...
class MyMultiSelectWidget(widgets.SelectMultiple):
def __init__(self, count=None, *args, **kwargs):
super().__init__(*args, **kwargs)
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
options = super(MyMultiSelectWidget, self).create_option(name, value, label, selected, index, subindex=None, attrs=None)
return options
我对 Django 很陌生,我觉得我遇到了很多它的边缘情况,所以我很感激任何帮助!
更新 #1:
我已经意识到,在我的表单的 init 中,我不是调用该字段的 label_from_instance 函数,而是定义它与self.fields['studentCheckbox'].label_from_instance = lambda obj: "%s (%s)" % (students.get(pk=obj.pk)['name'], students.get(pk=obj.pk)['count']).
因此,我已经注释掉了该行,现在调用了被覆盖的函数。虽然我现在可以访问 obj 的计数,但它仍然没有出现在呈现的 HTML 中。更新的代码如下。
class MyModelMultipleChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, obj):
print(obj.count) # this works now
if hasattr(obj, 'count'):
# no error, but not appearing in rendered html
self.widget.attrs.update({obj.pk: {'data-count': obj.count}})
return obj
class FiltersForm(forms.Form):
...
studentCheckbox = MyModelMultipleChoiceField(queryset=Student.objects.all(), required=False)
...
def __init__(self, *args, **kwargs):
super(FiltersForm, self).__init__(*args, **kwargs)
students = Student.objects.annotate(count=Count(...))
# These objects feed into the overridden label_from_instance function
self.fields['studentCheckbox'].queryset = students
#self.fields['studentCheckbox'].label_from_instance = lambda obj: "%s (%s)" % (students.get(pk=obj.pk)['name'], students.get(pk=obj.pk)['count'])
【问题讨论】:
标签: django django-forms django-widget