The initial value of the Django form field when validation fails

how to set the value of a field element after submitting the form, but failed to validate? eg.

if form.is_valid(): form.save() else: form.data['my_field'] = 'some different data' 

I really don't want to put it in a view, although I would rather have it as part of a form class.

thanks

+7
django django-forms
source share
3 answers

I finished work

 if request.method == 'POST': new_data = request.POST.copy() form = MyForm(data=new_data) if form.is_valid(): form.save() else: new_data['myField'] = 'some different data' 

Hope this helps someone

+6
source share

The documentation says:

If you have an associated form instance and want to change the data in some way, or if you want to associate an unrelated form instance with some data, create another instance of the form . It is not possible to change data in an instance of a form. After the form instance has been created, you should consider its immutable data , regardless of whether it has data or not.

I can't believe your code is working. But good. Based on the documentation, I would do it like this:

 if request.method == 'POST': data = request.POST.copy() form = MyForm(data) if form.is_valid(): form.save() else: data['myField'] = 'some different data' form = MyForm(initial=data) 
+16
source share

You can put it in the form class as follows:

 class MyForm(forms.Form): MY_VALUE = 'SOMETHING' myfield = forms.CharField( initial=MY_VALUE, widget=forms.TextInput(attrs={'disabled': 'disabled'}) def __init__(self, *args, **kwargs): # If the form has been submitted, populate the disabled field if 'data' in kwargs: data = kwargs['data'].copy() self.prefix = kwargs.get('prefix') data[self.add_prefix('myfield')] = MY_VALUE kwargs['data'] = data super(MyForm, self).__init__(*args, **kwargs) 

How it works, checks to see if any data has been passed to the form constructor. If it does, it copies it (the raw data is unchanged), and then puts the initial value in the value before continuing to instantiate the form.

+1
source share

All Articles