Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Treatment of empty ImmutableMultiDict on form init #444

Closed
anthonyjb opened this issue Aug 24, 2018 · 1 comment
Closed

Treatment of empty ImmutableMultiDict on form init #444

anthonyjb opened this issue Aug 24, 2018 · 1 comment

Comments

@anthonyjb
Copy link

I primarily use Flask as my web framework, when I initialize forms my code often looks something very similar to this:

@members_only
def update_my_account(member):

    # Initialize the about form
    form = UpdateMyAccountForm(request.form, obj=member)

    ...

Pre 2.2.x if request.form returned an empty ImmutableMultiDict then the form fields would be updated with the values of the obj. So in my example above on a GET request my form would contain values from the member instance, however, post 2.2.x this behaviour has changed. Now the ImmutableMultiDict appears to be treated as an empty submission and on GET my form is field values are all empty.

Now as we use WTForms and Flask as components in our own framework I wrap a significant amount of WTForms including the Form class so I was easily able to work around this with the following patch in my __init__ method:

class BaseForm(Form):

    def __init__(self, formdata=None, obj=None, prefix='', data=None, meta=None,
            **kwargs):

        # When wtforms when to 2.2.x if the `formdata` is sent as an empty
        # ImmutableMultiDict then this is seen treated as an empty submission
        # and overrides the values of obj, data and keywords. To avoid this we
        # check for an empty `formdata` value and convert it to None.
        if isinstance(formdata, ImmutableMultiDict) and len(formdata) == 0:
            formdata = None

        super().__init__(formdata, obj, prefix, data, meta, **kwargs)

I don't think this is a bug with WTForms but it is quite a big change in behaviour that can break functionality depending on how you initialise forms (I don't think this approach is unique to Flask), so I thought I'd raise it here and hope that the above patch might be useful to anyone else who stumbles across the same issue in their project and to also humbly request that a note regarding this is included in the release notes.

@davidism
Copy link
Member

Duplicate of #402

@davidism davidism marked this as a duplicate of #402 Aug 24, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants