【发布时间】:2026-01-07 12:10:02
【问题描述】:
由于 BD 设计取决于值,数据存储在不同的单元格中,我必须动态添加表单字段。我在想这个:
class EditFlatForm(BaseModelForm):
on_sale = forms.BooleanField(required=False)
on_rent = forms.BooleanField(required=False)
class Meta:
model = Flat
fields = ('title', 'flat_category', 'description')
...
def __init__(self, *args, **kwargs):
super(EditFlatForm, self).__init__(*args,**kwargs)
flat_properties = FlatProperty.objects.all()
for p in flat_properties:
if p.type_value == 1:
# Text
setattr(self, p.title, forms.CharField(label=p.human_title, required=False))
elif p.type_value == 2:
# Number
setattr(self, p.title, forms.IntegerField(label=p.human_title, required=False))
else:
# Boolean
setattr(self, p.title, forms.BooleanField(label=p.human_title, required=False))
但是字段没有被添加,我错过了什么?
【问题讨论】:
-
你当然不应该从 BaseModelForm 继承。
-
BaseModelForm 只是我用来处理标签的一个类,为什么不用呢?
-
也许是
self.fields[p.title] = forms....?假设p.title是一个字符串 -
@MihaiZamfir omg,当然,我在想什么,干杯伙伴,添加它作为回应,我会接受它,但我认为这个问题将是非常多余的
-
抱歉,我以为是forms.BaseModelForm。