django形式:动态更改formfield的属性

时间:2011-05-13 08:33:59

标签: python django django-forms

我的表格如下:

class ConsentFormTpl(forms.Form):
    title =  forms.CharField()
    message = forms.CharField(widget=EditorWidget,label='Description')
    acknowledge = forms.BooleanField(label="Require acknowledgement?")
    deadline = forms.DateField(widget=CalendarTimeWidget,label="Acknowledge By")
    start_time = forms.DateTimeField(widget=CalendarTimeWidget)
    end_time = forms.DateTimeField(widget=CalendarTimeWidget)
    availClass  = forms.ModelChoiceField(queryset=SchoolClass.objects.all(),empty_label="Select a class",label='Class')
    consent = forms.BooleanField()
    students = forms.ModelMultipleChoiceField(label="",\
        queryset=User.objects.filter(groups__name='Students').extra(select={'user_name':"first_name || ' ' || last_name"}), \
        widget=FilteredSelectMultiple("Students",is_stacked=False))
    where =  forms.CharField()
    form_name = forms.CharField(label='Save as:')


    def __init__(self,data=None,draft=False):
        super(ConsentFormTpl,self).__init__(data)
        self.draft = draft

        self.acknowledge.required = False
        self.deadline.required = False
        self.start_time.required = False
        self.end_time.required = False
        self.availClass.required = False
        self.consent.required = False
        self.where.required = False

        if draft:
            self.title.required = False
            self.message.required = False
            self.students.required = False
            self.form_name.required = True
        else:
            self.form_name.required = False

根据草稿的值,我想更改某些字段的属性(必需),这是init方法中的内容。

但是我遇到了以下消息:

'ConsentFormTpl' object has no attribute 'acknowledge'

任何人都知道为什么?

1 个答案:

答案 0 :(得分:18)

这些字段在表单实例上不可用作属性。它们在self.fields中可用作字典元素。所以:

self.fields['acknowledge'].required = False

等等。