views:

602

answers:

2

Hi, how do I set the value of a field element after a form has been submitted but has failed validation? e.g.

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

I don't really want to put it in the view though and would rather have it as part of the form class.

Thanks

+2  A: 

I ended up doing

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

John
+2  A: 

The documentation says:

If you have a bound Form instance and want to change the data somehow, or if you want to bind an unbound Form instance to some data, create another Form instance. There is no way to change data in a Form instance. Once a Form instance has been created, you should consider its data immutable, whether it has data or not.

I cannot really believe that your code works. But ok. Based on the documentation I would do it this way:

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)
Felix Kling