动态更新 Django 表单中的 MultipleChoiceField 选项属性



我正在使用 Django Forms 来实现我的 Web 应用程序的前端过滤器功能,并且我正在进行一些字段自定义,以便我可以显示带有自定义标签的多选复选框,如下所示:

[x] 道格·滑稽 (1( [ ] 斯基特情人节(5( [x] 帕蒂蛋黄酱(3( [ ] 罗杰·克洛茨 (9(



选择一个选项后,我能够通过覆盖我的 Formsinit方法动态更新复选框字段标签(特别是计数(,如下所示:

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(并在此过程中设置数据计数属性。但是,由于某种原因,label_from_instance函数没有从我的表单初始化中的lambda 调用调用 (self.fields['studentCheckbox'].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 表单字段选择、添加属性(的启发,我终于让它工作了。事实证明,我确实需要对 SelectMultiple 小部件进行子类化。然后,我可以简单地在其上设置一个 count 属性,该属性可以通过<input class="form-check-input" type="checkbox" data-count="{{widget.data.count}}"在模板中访问。

class MyModelMultipleChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, obj):
print(obj.count) # this works now
if hasattr(obj, 'count'):
self.widget.count = obj.count
# or, alternatively, add to widgets attrs...
# self.widget.custom_attrs.update({obj.pk: {'count': obj.count}})
return "%s (%s)" % (obj, obj.count)
class MyMultiSelectWidget(widgets.SelectMultiple):
def __init__(self, *args, **kwargs):
self.count = None
# self.custom_attrs = {}
super().__init__(*args, **kwargs)
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
index = str(index) if subindex is None else "%s_%s" % (index, subindex)
if attrs is None:
attrs = {}
option_attrs = self.build_attrs(self.attrs, attrs) if self.option_inherits_attrs else {}
if selected:
option_attrs.update(self.checked_attribute)
if 'id' in option_attrs:
option_attrs['id'] = self.id_for_label(option_attrs['id'], index)
# alternatively, setting the attributes here for the option
#if len(self.custom_attrs) > 0:
#    if value in self.custom_attrs:
#        custom_attr = self.custom_attrs[value]
#        for k, v in custom_attr.items():
#            option_attrs.update({k: v})
return {
'name': name,
'count': str(self.count),
'value': value,
'label': label,
'selected': selected,
'index': index,
'attrs': option_attrs,
'type': self.input_type,
'template_name': self.option_template_name,
}
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'])

如果有其他更优化的实现,请告诉我!

相关内容

  • 没有找到相关文章

最新更新