更改表单元素名称和ID

时间:2012-05-30 17:12:40

标签: python django

我有以下内容,它根据实例中的type动态创建一个字段:

class LVariableForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(someObj, self).__init__(*args, **kwargs)

        if self.instance:
            if self.instance.type == 'bool':
                self.fields['data'] = BooleanField()
            if self.instance.type == 'date':
                self.fields['data'] = DateField()
            if self.instance.type == 'float':
                self.fields['data'] = DecimalField()
            if self.instance.type == 'text':
                self.fields['data'] = TextInput()
            self.fields['data'].label = self.instance.name

    class Meta:
        model = LVariable

唯一的问题是创建的元素名称为data,ID为1_data

 <input name="data" id="1_data" dojoType="dijit.form.NumberTextBox">

我该如何更改?

1 个答案:

答案 0 :(得分:0)

因为我在表单中使用了相同表单字段的多个实例,所以最好的办法是:

# forms.py
class LBooleanVForm(Form):
    def __init__(self,LTV, *args, **kwargs):
        super(LBooleanVForm, self).__init__(*args, **kwargs)
        self.fields[LTV.name] = BooleanField()

class LFloatVForm(Form):
    def __init__(self,LTV, *args, **kwargs):
        super(LFloatVForm, self).__init__(*args, **kwargs)
        self.fields[LTV.name] = FloatField()

class LTextVForm(Form):
    def __init__(self,LTV, *args, **kwargs):
        super(LTextVForm, self).__init__(*args, **kwargs)
        self.fields[LTV.name] = TextInput()

class LDateVForm(Form):
    def __init__(self,LTV, *args, **kwargs):
        super(LDateVForm, self).__init__(*args, **kwargs)
        self.fields[LTV.name] = DateField()

# views.py
ltv = LV.objects.filter(l_t=lt)
lvForm = []
for ltVars in ltv:
    if ltVars.type == 'bool':
        newField = LetterBooleanVariableForm(ltVars)
    elif ltVars.type == 'date':
        newField = LetterDateVariableForm(ltVars)
    elif ltVars.type == 'float':
        newField = LetterFloatVariableForm(ltVars)
    elif ltVars.type == 'text':
        newField = LetterTextVariableForm(ltVars)
    else:
        raise Http404
    lvForm.append(newField)