简体   繁体   English

在__init__之后但在清洁之前,在django中更改表单字段值

[英]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: 无效的事情:

  • Setting the initial parameter. 设置初始参数。 Since there is a value present, it will be ignored 由于存在一个值,它将被忽略
  • Using cleaned values. 使用清理后的值。 The form is not cleaned at this stage, since it is not valid. 由于该表单无效,因此在此阶段未清理该表单。 Because of this 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 . 有两种形式,即formform_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM