具有一般关系的模型的形式__init__中的初始值 [英] Initial value in form's __init__ for the model with generic relation
问题描述
我有一个具有通用关系的模型,如下所示:
I have a model with generic relation like this:
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()内部的选择中.
To make the life easier for the user I have modified the form. The idea was to have one field with choices instead of multiple. For that I have merged fields into choices inside of form's 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字段提供初始值.
Till now everything was working fine, but now I have to provide initial value for content_object field.
我已将此代码添加到init()中,但是它不起作用:
I have added this code to init() but it is not working:
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内设置初始值?谢谢!
Any suggestions why I cannot set initial value inside of init? Thanks!
P.S.调试输出对我来说还可以,但是初始设置根本没有设置.
P.S. Debug output looks for me ok, but initial is not set at all.
print(self.fields['content_object'].choices) --> [['type:32-id:10050', 'Value1'], ['type:32-id:10056', 'Value2']]
print(form_value) --> type:32-id:10056
推荐答案
我在此处:
如果您已经在Form类中调用了super(). init ,应该更新form.initial字典,而不是field.initial财产.如果您学习form.initial(例如在调用super(). init ),它将包含所有字段的值.该字典中的值为None将覆盖该字段.值
If you have already called super().init in your Form class, you should update the form.initial dictionary, not the field.initial property. If you study form.initial (e.g. print self.initial after the call to super().init), it will contain values for all the fields. Having a value of None in that dict will override the field.initial value
该问题的解决方案是仅添加另一行:
The solution to the problem was then just adding one additional line:
self.initial['content_object'] = form_value
这篇关于具有一般关系的模型的形式__init__中的初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!