我已经编写了一个工厂函数来创建动态表单,正如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 })
答案 0 :(得分: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()
)
答案 1 :(得分:1)
使用SortedDict
(djangos实施OrderedDict
2.7 +)
https://github.com/django/django/blob/master/django/utils/datastructures.py