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

2022-01-18 00:00:00 python django widget forms

问题描述

我的表单域如下所示:

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

    class Meta:
        model = Foo

上面的代码出现如下错误:init() got an unexpected keyword argument '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'})
)

应该修复它.

相关文章