Django 创建一个使用小部件只读的表单字段

Django 创建一个使用小部件只读的表单字段

问题描述:

我的表单域如下所示:

class FooForm(ModelForm):
    somefield = models.CharField(
        widget=forms.TextInput(attrs={'readonly':'readonly'})
    )

    class Meta:
        model = Foo

上面的代码出现如下错误:init()得到了一个意外的关键字参数'widget'

Geting an error like the following with the code above: init() got an unexpected keyword argument 'widget'

我认为这是对表单小部件的合法使用?

I thought this is a legitimate use of a form widget?

您应该使用表单字段而不是模型字段:

You should use a form field and not a model field:

somefield = models.CharField(
    widget=forms.TextInput(attrs={'readonly': 'readonly'})
)

替换为

somefield = forms.CharField(
    widget=forms.TextInput(attrs={'readonly': 'readonly'})
)

应该修复它.