1

我已经编写了一个工厂函数来创建动态表单,正如 James Bennett 的有用帖子http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/末尾所述。

该表单工作得很好,但项目显示的顺序有点随机,因为(我假设)这fields是一个字典(请参见下面的代码示例)。如何为表单域规定一个定义的显示顺序?

def make_form(assessment):
    '''
    Factory function to build and return dynamic AssessmentForms
    '''
    entries = assessment.entry_set.all()

    fields = {}

    for entry in entries:
        fields[entry.name] = forms.ChoiceField(
            required=False,
            initial=entry.rating,
            choices=CHOICES,
            widget=forms.RadioSelect()
        )

    return type('AssessmentForm', (forms.BaseForm,), { 'base_fields': fields })
4

2 回答 2

2

富田裕二是对的。您可以使用例如:

from django.utils.datastructures import SortedDict

fields = SortedDict()

for entry in entries:
    fields[entry.name] = forms.ChoiceField(
        required=False,
        initial=entry.rating,
        choices=CHOICES,
        widget=forms.RadioSelect()
    )
于 2013-01-24T11:03:48.513 回答
1

使用SortedDict(2.7+的djangos实现OrderedDict

https://github.com/django/django/blob/master/django/utils/datastructures.py

于 2013-01-24T09:59:44.150 回答