How does Django Know the Order to Render Form Fields?

后端 未结 14 1419
不知归路
不知归路 2020-11-28 05:21

If I have a Django form such as:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = fo         


        
14条回答
  •  旧巷少年郎
    2020-11-28 06:06

    As of Django 1.7 forms use OrderedDict which does not support the append operator. So you have to rebuild the dictionary from scratch...

    class ChecklistForm(forms.ModelForm):
    
      class Meta:
        model = Checklist
        fields = ['name', 'email', 'website']
    
      def __init__(self, guide, *args, **kwargs):
        self.guide = guide
        super(ChecklistForm, self).__init__(*args, **kwargs)
    
        new_fields = OrderedDict()
        for tier, tasks in guide.tiers().items():
          questions = [(t['task'], t['question']) for t in tasks if 'question' in t]
          new_fields[tier.lower()] = forms.MultipleChoiceField(
            label=tier,
            widget=forms.CheckboxSelectMultiple(),
            choices=questions,
            help_text='desired set of site features'
          )
    
        new_fields['name'] = self.fields['name']
        new_fields['email'] = self.fields['email']
        new_fields['website'] = self.fields['website']
        self.fields = new_fields 
    

提交回复
热议问题