Can I add non existing field to form with WebTest?
Asked Answered
R

2

5

I am testing a form using WebTest. However, somes fields are created dynamically using JS, and thus these fields are not in the Form. I have an error when I try to set one of these fields:

>>> resp.form['new_field'] = 'value'
or
>>> resp.form.set('new_field', 'value')
or
>>> resp.form.set('new_field', 'value', index=0)
or 
>>> resp.form['new_field'].force_value('value')

*** AssertionError: No field by the name 'new_field' found

Is there a way to create a field ?

Rombert answered 28/3, 2014 at 9:15 Comment(0)
V
11

You need to add the new field to both fields and field_order:

from webtest.forms import Text
def add_dynamic_field(form, name, value):
    """Add an extra text field to a form. More work required to support files"""
    field = Text(form, 'input', None, None, value)
    form.fields[name] = [field]
    form.field_order.append((name, field))

add_dynamic_field(resp.form, 'newfield', 'some value')
Virginavirginal answered 26/5, 2014 at 21:32 Comment(1)
form.fields now stores values as a list.Mendacious
C
1

Updated @lambacck code to handle file fields as well. pos is required on Python3 as well.

from webtest.forms import Text, File
from webtest import Upload


def add_dynamic_field(form, name, value):
    field_cls = File if isinstance(value, Upload) else Text
    field = field_cls(form, tag='input', name=name, value=value, pos=999)
    form.fields[name] = [field]
    form.field_order.append((name, field))
Connell answered 12/6, 2017 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.