[英]Change form field value in django, after __init__ but before cleaning
I want to reset the value of some fields in my django form to None
, inside the __init__
method of my form. 我想将表单的__init__
方法中的django表单中的某些字段的值重置为None
。
This is what I have so far: 这是我到目前为止的内容:
class MyFormForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['field1', ...]
field1 = forms.IntegerField(max_value=100)
def __init__(self, *args, **kwargs):
values_changed = kwargs.pop('values_changed', False)
super(MyFormForm, self).__init__(*args, **kwargs)
self.data = self.data.copy()
if not values_changed:
for field in self.fields:
self.data[field] = None
Unfortunately, when the form is displayed in my template, the value that has been POSTed is still in it. 不幸的是,当表单显示在我的模板中时,已经过POST的值仍在其中。 How do I get rid of the value, so that the change takes effect in the template, which renders the form? 如何删除值,以使更改在呈现表单的模板中生效?
Things that don't work: 无效的事情:
cleaned_data
does not exist 因此, cleaned_data
不存在 I'm accessing the values like this: 我正在访问这样的值:
{{ form.field1.value|default_if_none:"Please enter." }}
edit: I just tried 编辑:我刚刚尝试
{{ form.data.field1|default_if_none:"Please enter." }}
no change. 没变。
I'm a moron. 我是白痴。 There were two forms, form
and form_2
. 有两种形式,即form
和form_2
。
I used the wrong variable name. 我使用了错误的变量名。 My bad. 我的错。 It works like it should with the code above. 它与上面的代码一样工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.