更改Django表单属性' required' by bool in template

时间:2016-05-04 12:00:38

标签: django

我试图让管理员选择是否为用户创建字段。

我的表单看起来像这样。

class StudentDetailForm(MyForm):
    first_name = fields.CharField(required=True)
    last_name = fields.CharField(required=True)
    date_of_birth = MyDateField(required=True, widget=MyDateInput(attrs{'class': 'dobpicker'}))
    id_number2 = fields.CharField(required=True, label='PPS Number')
    note = fields.CharField(required=False,
          widget=forms.Textarea(attrs={'cols': '25', 'rows': '2'}))


class Meta:
    model = Person
    fields = ['first_name', 'last_name', 'date_of_birth', 'id_number2', 'gender', 'note']

等...

这是我尝试更改必填字段的方式。它遍历所有字段,并在管理页面上显示可见或必需的复选框。

然后每个都显示在表单页面上,其中包含必需值或非值。

student_form = StudentDetailForm(None, data=request.POST or None)
mother_form = ParentDetailForm(None, data=request.POST or None, prefix='g1', instance=mother)
father_form = ParentDetailForm(None, data=request.POST or None, prefix='g2', instance=father)
family_form = FamilyDetailForm(None, data=request.POST or None)

# student_form, mother_form, father_form, family_form = get_web_intake_forms(school, request.POST or None, requestpps)

for name, value in webfields.items():
    if not value['visible']:
        # name is actual name plus : plus a number
        # split up to name and number
        bits = name.split(':')
        fname = bits[0]
        formnum = bits[1]
        if formnum == '1':
            del student_form.fields[fname]
        elif formnum == '2':
            del mother_form.fields[fname]
        elif formnum == '3':
            del father_form.fields[fname]
        elif formnum == '4':
            del family_form.fields[fname]

    elif value['required']:
        # name is actual name plus : plus a number
        # split up to name and number
        bits = name.split(':')
        fname = bits[0]
        formnum = bits[1]
        if formnum == '1':
            student_form.base_fields[fname].required = True
        elif formnum == '2':
            mother_form.fields[fname].required = True
        elif formnum == '3':
            father_form.fields[fname].required = True
        elif formnum == '4':
            family_form.base_fields[fname].required = True

    elif not value['required']:
        # name is actual name plus : plus a number
        # split up to name and number
        bits = name.split(':')
        fname = bits[0]
        formnum = bits[1]
        if formnum == '1':
            student_form.base_fields[fname].required = False
        elif formnum == '2':
            mother_form.fields[fname].required = False
        elif formnum == '3':
            father_form.fields[fname].required = False
        elif formnum == '4':
            family_form.base_fields[fname].required = False

我试过base_fields哪种工作但有点乱。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可能不希望更改base_fields - 更新StudentDetailForm类的字段,而不仅仅是特定的form实例

根据视图的其余部分,设置form.fields['first_name'].required应该有效。

但是,通常最好在表单的self.fields['first_name'].required方法中设置__init__。我不知道你会怎么做,因为你似乎有多个表格和许多字段名称,所以这里有一个更简单的例子。

class MyForm(forms.Form):
    first_name = forms.CharField()

    def __init__(self, *args, **kwargs):
        first_name_required = kwargs.pop('first_name_required')
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].required = first_name_required

然后,您将初始化您的表单,如:

form = MyForm(data=request.POST, first_name_required=True)