2013-01-24 64 views
1

我寫了一個工廠函數來創建動態表單,如James Bennett的有用帖子末尾所述http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/以動態Django表格定義字段順序

表格工作得很好,但項目顯示的順序有點隨機,因爲(我假設)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 }) 

回答

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() 
    )