我有一个具有 EmbeddedModelField (embedmodel) 的模型 (parentmodel)。这基本上是 MongoDB 中的文档。下面是模型类
class embedmodel(models.Model):
sendto = models.CharField(max_length=10)
sendtouser = models.CharField(max_length=15)
sendtogroup = models.CharField(max_length=15)
class parentmodel(models.Model):
name = models.CharField(max_length=30, unique=True, primary_key=True)
type = models.CharField(max_length=11)
enabled = models.BooleanField()
rule = models.EmbeddedModelField(model_container=embedmodel)
class Meta:
managed = False
db_table = 'parentmodel'
这就是我在 mongodb 中的文档的样子
{
'name': 'rule1',
'type': 'static',
'enabled': True,
'rule': {
'sendto': 'external',
'sendtouser': 'sam',
'sendtogroup': 'vendor'
}
}
我正在尝试创建一个表单来帮助我创建新规则,这就是我在 forms.py 中的内容,我也想自定义表单字段。
class RulesForm(forms.ModelForm):
name = forms.CharField(max_length=30, required=True)
type = forms.CharField(max_length=11, required=True)
enabled = forms.BooleanField(widget=forms.CheckboxInput)
class Meta:
model = parentmodel
fields = ['name', 'type', 'enabled', 'rule']
如何自定义从 embedmodel 中显示的字段?我尝试了以下但没有运气。
class RulesForm(forms.ModelForm):
name = forms.CharField(max_length=30, required=True)
type = forms.CharField(max_length=11, empty_value="UserDefined", required=True
enabled = forms.BooleanField(widget=forms.CheckboxInput)
sendto = forms.ChoiceField(widget=forms.Select, choices=[(1, 'External'), (2, 'Internal')])
sendtouser = forms.CharField(max_length=30, required=False)
sendtogroup = forms.CharField(max_length=30, required=False)
class Meta:
model = Rules
fields = ['name', 'type', 'enabled', 'rule']
和
class RulesForm(forms.ModelForm):
name = forms.CharField(max_length=30, required=True)
type = forms.CharField(max_length=11, empty_value="UserDefined", required=True
enabled = forms.BooleanField(widget=forms.CheckboxInput)
embedmodel.sendto = forms.ChoiceField(widget=forms.Select, choices=[(1, 'External'), (2, 'Internal')])
embedmodel.sendtouser = forms.CharField(max_length=30, required=False)
embedmodel.sendtogroup = forms.CharField(max_length=30, required=False)
class Meta:
model = Rules
fields = ['name', 'type', 'enabled', 'rule']