Django set field value after a form is initialized

后端 未结 9 1904
陌清茗
陌清茗 2020-12-12 14:50

I am trying to set the field to a certain value after the form is initialized.

For example, I have the following class.

class CustomForm(forms.Form)         


        
相关标签:
9条回答
  • 2020-12-12 15:02

    To throw yet another way into the mix: this works too, with a bit more modern notation. It just works around the fact that a QueryDict is immutable.

    >>> the_form.data = {**f.data.dict(), 'some_field': 47}
    >>> the_form['some_field'].as_widget()
    '<input type="hidden" name="some_field" value="47"
            class="field-some_field" id="id_some_field">'
    
    0 讨论(0)
  • 2020-12-12 15:13

    in widget use 'value' attr. Example:

    username = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={'readonly': True, 'value': 'CONSTANT_VALUE'}),
    )
    
    0 讨论(0)
  • 2020-12-12 15:17

    If you want to do it within the form's __init__ method for some reason, you can manipulate the initial dict:

    class MyForm(forms.Form):
        my_field = forms.CharField(max_length=255)
    
        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(*args, **kwargs)
            self.initial['my_field'] = 'Initial value'
    
    0 讨论(0)
  • 2020-12-12 15:18

    If you have initialized the form like this

    form = CustomForm()
    

    then the correct way as of Jan 2019, is to use .initial to replace the data. This will replace the data in the intial dict that goes along with the form. It also works if you have initialized using some instance such as form = CustomForm(instance=instance)

    To replace data in the form, you need to

    form.initial['Email'] = GetEmailString()
    

    Generalizing this it would be,

    form.initial['field_name'] = new_value
    
    0 讨论(0)
  • 2020-12-12 15:22

    Since you're not passing in POST data, I'll assume that what you are trying to do is set an initial value that will be displayed in the form. The way you do this is with the initial keyword.

    form = CustomForm(initial={'Email': GetEmailString()})
    

    See the Django Form docs for more explanation.

    If you are trying to change a value after the form was submitted, you can use something like:

    if form.is_valid():
        form.cleaned_data['Email'] = GetEmailString()
    

    Check the referenced docs above for more on using cleaned_data

    0 讨论(0)
  • 2020-12-12 15:22

    If you've already initialized the form, you can use the initial property of the field. For example,

    form = CustomForm()
    form.fields["Email"].initial = GetEmailString()
    
    0 讨论(0)
提交回复
热议问题