2016-09-28 23 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