我有一个像这样的通用关系的模型:
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()中的选项。
def __init__(self, *args, **kwargs):
super(AdminTaskForm, self).__init__(*args, **kwargs)
# combine object_type and object_id into a single 'generic_obj' field
# getall the objects that we want the user to be able to choose from
available_objects = list(Event.objects.all())
available_objects += list(Contest.objects.all())
# now create our list of choices for the <select> field
object_choices = []
for obj in available_objects:
type_id = ContentType.objects.get_for_model(obj.__class__).id
obj_id = obj.id
form_value = "type:%s-id:%s" % (type_id, obj_id) # e.g."type:12-id:3"
display_text = str(obj)
object_choices.append([form_value, display_text])
self.fields['content_object'].choices = object_choices
直到现在一切正常,但现在我必须为content_object字段提供初始值。
我已将此代码添加到init()但它无效:
initial = kwargs.get('initial')
if initial:
if initial['content_object']:
object = initial['content_object']
object_id = object.id
object_type = ContentType.objects.get_for_model(object).id
form_value = "type:%s-id:%s" % (object_type, object_id)
self.fields['content_object'].initial = form_value
为什么我无法在init中设置初始值的任何建议?谢谢!
P.S。调试输出对我来说没问题,但是根本没有设置初始值。
print(self.fields['content_object'].choices) --> [['type:32-id:10050', 'Value1'], ['type:32-id:10056', 'Value2']]
print(form_value) --> type:32-id:10056
答案 0 :(得分:0)
我找到了一个很好的答案here:
如果你已经在Form类中调用了super()。 init ,那么 应该更新form.initial字典,而不是field.initial 属性。如果你研究form.initial(例如,打印self.initial后 调用super()。 init ),它将包含所有字段的值。 在该dict中具有None值将覆盖field.initial 值
问题的解决方案只是增加了一行:
undefined