2016-09-28 34 views
0

初始值我有一个通用的关系的模式是这样的:形式的__init__的模型与通用的关系

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 

为什么我不能设置初始化的内部初始值有什么建议?谢谢!

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

我已经找到一个很好的回答我的问题here

如果您已经称为超()。 init在你的Form类中,你的 应该更新form.initial字典,而不是field.initial 属性。如果学习form.initial(例如,在 调用super()。init)后打印self.initial,它将包含所有字段的值。 在字典有无的值将覆盖field.initial 值

到问题的解决方法,然后仅仅增加一个附加行:

self.initial['content_object'] = form_value