我有以下型号:
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的默认值呈现为具有适当选择的Select。但是form2只有两个空白的TextInput字段。知道如何确保从modelform_factory方法生成的表单尊重这些属性吗?
答案 0 :(得分:0)
如果您希望为每个对象看到一系列编辑表单,我相信您需要在使用生成的工厂时设置queryset参数。默认行为是显示所有对象,以及空表单。
def MyView(request):
...
form2 = MyFormFactory(instance=model, queryset=MyModel.objects.all())
这link可能会有所帮助。
带上一粒盐。这是我第一天玩Python。