如何在django中修改绑定形式的字段的绑定值?

时间:2022-10-15 19:23:02

I override the __init__ method of my Form. I can set the initial value by doing the following:

我重写了Form的__init__方法。我可以通过执行以下操作来设置初始值:

self.fields['fieldname'].initial = ....

But given that it is bound, calling the above has no effect. I tried doing this:

但鉴于它受到约束,调用上述内容无效。我试过这样做:

self.fields['fieldname'].bound_data = ....

but this does not work. Is there a way to do this ?

但这不起作用。有没有办法做到这一点 ?

1 个解决方案

#1


10  

You can update the form's data dict

您可以更新表单的数据字典

self.data['fieldname'] = new_value

bound_data is a method, not an attribute, so you can't set the value there.

bound_data是一个方法,而不是一个属性,因此您无法在那里设置值。

request.GET and request.POST are immutable, unless you create a copy(). You could do the copy in your __init__ method, or before you bind the form.

request.GET和request.POST是不可变的,除非你创建一个副本()。您可以在__init__方法中或绑定表单之前执行复制。

data = request.POST.copy()
form = MyForm(data=data)

#1


10  

You can update the form's data dict

您可以更新表单的数据字典

self.data['fieldname'] = new_value

bound_data is a method, not an attribute, so you can't set the value there.

bound_data是一个方法,而不是一个属性,因此您无法在那里设置值。

request.GET and request.POST are immutable, unless you create a copy(). You could do the copy in your __init__ method, or before you bind the form.

request.GET和request.POST是不可变的,除非你创建一个副本()。您可以在__init__方法中或绑定表单之前执行复制。

data = request.POST.copy()
form = MyForm(data=data)