Python 形式为'的初始值;具有泛型关系的模型的s_uuinit_uu

Python 形式为'的初始值;具有泛型关系的模型的s_uuinit_uu,python,django,Python,Django,我有一个通用关系的模型,如下所示: content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) content_object = GenericForeignKey('content_type', 'object_id') 为

我有一个通用关系的模型,如下所示:

  content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True)

  object_id = models.PositiveIntegerField(blank=True, null=True)

  content_object = GenericForeignKey('content_type', 'object_id')
为了方便用户,我修改了表单。这个想法是让一个字段有选择,而不是多个字段。为此,我将字段合并到表单的init()中的选项中

为什么我不能在init内部设置初始值,有什么建议吗?谢谢

另外,调试输出看起来还可以,但初始值根本没有设置

print(self.fields['content_object'].choices) --> [['type:32-id:10050', 'Value1'], ['type:32-id:10056', 'Value2']]
print(form_value) --> type:32-id:10056

对于我的问题,我找到了一个很好的答案:

如果您已经在表单类中调用了super()。init,那么 应该更新form.initial字典,而不是field.initial 财产。如果您学习表单首字母(例如,在 调用super()。init),它将包含所有字段的值。 如果该dict中的值为None,则会覆盖字段。初始值 价值观

然后,问题的解决方案只是增加一行:

self.initial['content_object'] = form_value
print(self.fields['content_object'].choices) --> [['type:32-id:10050', 'Value1'], ['type:32-id:10056', 'Value2']]
print(form_value) --> type:32-id:10056
self.initial['content_object'] = form_value