禁用没有显式声明的Django ModelForm字段

2024-04-25 21:31:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

class MyModel(models.Model):
    input_field = model.CharField(max_length=100)


class MyModelForm(forms.ModelForm):

    input_field = forms.CharField(disabled=True)    

    class Meta:
        model = MyModel

我也读过docs

When you explicitly instantiate a form field like this, it is important to understand how ModelForm and regular Form are related.

...

Fields defined declaratively are left as-is, therefore any customizations made to Meta attributes such as widgets, labels, help_texts, or error_messages are ignored; these only apply to fields that are generated automatically.

Similarly, fields defined declaratively do not draw their attributes like max_length or required from the corresponding model. If you want to maintain the behavior specified in the model, you must set the relevant arguments explicitly when declaring the form field.

有没有可能将kwargs传递给表单字段,这样我就可以指定disabled=True,而不会失去ModelForm自省和定制的好处?我能吃我的蛋糕吗?你知道吗

我知道我可以通过在Meta类中使用widgets = {'input_field': widgets.TextInput(attrs={'readonly':'readonly'})来解决这个问题,但是我对是否有更好的方法感兴趣

同样不清楚的是,如上所述修改widgets属性是否会“继承”ModelForm将应用的默认配置,例如从底层模型推断max_length。你知道吗


Tags: thetoyoufieldinputmodelwidgetslength
1条回答
网友
1楼 · 发布于 2024-04-25 21:31:22

可能最简单的方法就是重写__init__。你知道吗

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['input_field'].disabled = True

相关问题 更多 >