我有以下模型:
class MyModel(models.Model):
myField = models.CharField()
myOtherField = models.CharField()
def __init__(self,*args,**kwargs):
super(MyModel,self).__init__(*args, **kwargs)
self._meta.get_field_by_name("myField")[0].default = get_default_value()
self._meta.get_field_by_name("myOtherField")[0]._choices = get_choices()
def get_default_value():
# obviously, this does more than just return a static value;
# how I actually get the default value for this field isn't relevant for this question
return "my default value"
def get_choices():
# as above, how this works is irrelevant
return [("one","one"),("two","two")]
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
MyFormFactory = modelform_factory(MyModel)
def MyView(request):
model = MyModel()
form1 = MyForm(instance=model)
form2 = MyFormFactory(instance=model)
return render_to_response('my_template.html',{'form1':form1, 'form2':form2})
Form1得到正确渲染,Myfield和Myotherfield的默认值作为选择的选择。但是 form2 只有两个空白的 TextInput 字段。知道如何确保从 modelform_factory 方法生成的表单尊重这些属性吗?