django表单:仅自定义标签

时间:2014-11-10 03:36:40

标签: django django-forms

有没有办法只自定义表单字段的标签而不指定字段类型?

例如,我对用户处理文档的权限有以下模型:

class Privilege(models.Model):
    user = models.OneToOneField(User)
    privCreate = models.BooleanField(default=False)
    privEdit = models.BooleanField(default=False)
    privDelete = models.BooleanField(default=False)
    ...

我有以下表格:

class PrivilegeForm(forms.ModelForm):
    privCreate = forms.BooleanField(label='Create a document')
    privEdit = forms.BooleanField(label='Edit a document')
    privDelete = forms.BooleanField(label='Delete a document')
    ...

    class Meta:
        model = Privilege
        fields = ('privCreate', 'privEdit', 'privDelete', ...)

有很多领域,这似乎违反了DRY。如果标签{?1}}与模型中的标签相同,我怎么才能自定义标签?

1 个答案:

答案 0 :(得分:1)

您可以使用.fields

__init__()中设置标签
class PrivilegeForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(PrivilegeForm, self).__init__(*args, **kwargs)

        self.fields['privCreate'].label = 'Create a document'
        ...