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

时间:2020-06-13 02:34:37

标签: django django-forms django-widget

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

[x] Doug Funny(1)
[]斯基特·瓦伦丁(5)
[x]帕蒂蛋黄酱(3)
[] Roger Klotz(9)

选择一个选项后,我可以通过以下方式覆盖我的Forms 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

我希望重写label_from_instance中的MyModelMultipleChoiceField函数,以便动态地(通过pk)访问obj并在该过程中设置data-count属性。但是由于某种原因,我的表单的 init 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'])

1 个答案:

答案 0 :(得分:0)

受到另一篇文章(Django form field choices, adding an attribute)答案的启发,我终于使它起作用了。事实证明,我确实需要继承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'])

如果还有其他更理想的实现,请告诉我!