我有这个密码:
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 regularForm
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
。你知道吗
可能最简单的方法就是重写
__init__
。你知道吗相关问题 更多 >
编程相关推荐