开发者

django forms: change attribute of formfield dynamically

开发者 https://www.devze.com 2023-03-05 20:56 出处:网络
I have a form like the one below: class ConsentFormTpl(forms.Form): title =forms.CharField() message = forms.CharField(widget=EditorWidget,label=\'Description\')

I have a form like the one below:

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=Fa开发者_如何学JAVAlse):
        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

Depending on the value of draft, I want to change the attributes (required) of some of the fields, which was what was in the init method.

However I encountered the following message:

'ConsentFormTpl' object has no attribute 'acknowledge'

Anyone knows why?


The fields aren't available as attributes on the form instance. They're available as dictionary elements in self.fields. So:

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

and so on.

0

精彩评论

暂无评论...
验证码 换一张
取 消