在运行时修改Django表单的最佳方法是什么?

| 我使用的代码是:
class VoteForm(forms.ModelForm):
    other_choice1 = forms.BooleanField(required=False)
    other_choice2 = forms.BooleanField(required=False)
    other_choice3 = forms.BooleanField(required=False)
    other_choice4 = forms.BooleanField(required=False)

    class Meta:
        model = Vote
        exclude = (\'choice\', \'other_choices\',)

    def __init__(self, poll_id, *args, **kwargs):
        super(VoteForm, self).__init__(*args, **kwargs)
        p = get_object_or_404(Poll, pk=poll_id)
        choices = p.choice_set.all()
        choices_len = len(choices)
        f = [\'other_choice1\',\'other_choice2\',\'other_choice3\',\'other_choice4\']
        for i in range(0,choices_len):
           self.fields[f[i]].label = str(choices[i])
        for i in range(choices_len,4):
           del self.fields[f[i]]
这是我发现在运行时修改表单字段的最佳方法。看起来有点像破解实现。明确定义的方法是什么? 谢谢, 亚历克斯     
已邀请:
        按照猴子修补Django表单类中所述使用
base_fields
吗? :
ContactForm.another_field = forms.CharField(...)
ContactForm.base_fields[\'another_field\'] = ContactForm.another_field
(或按此处http://snipt.net/danfreak/how-to-generate-a-dynamic-at-runtime-form-in-django/中的说明为“ 3”:
def make_contact_form(user):
    fields = { \'name\': forms.CharField(max_length=50),
               \'email\': forms.EmailField(),
               \'message\': forms.CharField(widget=forms.Textarea) }
    if not user.is_authenticated:
        fields[\'captcha\'] = CaptchaField()
    return type(\'ContactForm\', [forms.BaseForm], { \'base_fields\': fields })

)
    
        是的,这确实很hacky。但这是因为您的思维方向错误。您似乎想要的是关系中每个项目的一个复选框,而您正试图通过每个项目具有一个BooleanField来实现这一点。但这根本不是您应该考虑的方式-您应该考虑一个字段来表示该关系中的项目,并使用一个ChecbkoxMultipleSelect小部件来实际显示复选框。     

要回复问题请先登录注册