Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to pass extra value to given field's process_formdata method in WTForms
    text
    copied!<p>I have custom ZIPCodeField, but it require country to be given to work properly, it's easy for validation where i can just save it in _country attribute of the form in form's <strong>init</strong>(with fallback to country field in the same form), it looks like:</p> <pre><code>class ZIPCodeField(wtforms.TextField): def pre_validate(self, form): if not self.data: return country = country = getattr(form, '_country', form.data.get('country')) country = country.upper() if not validate_zip_code(self.data, country): raise ValueError(self.gettext(u'Invalid ZIP code.')) </code></pre> <p>but there is a problem with for process_formdata method (where I want to pass the received data trough simple filter to format the ZIP code correctly), we have no form instance, so seems like there are 2 solutions:</p> <p>Saving country on field level, like:</p> <pre><code>class ZIPCodeField(wtforms.TextField): def process_formdata(self, valuelist): if valuelist: self.data = format_zip_code(valuelist[0], self._country) else: self.data = '' class TestForm(wtforms.Form): zip_code = ZIPCodeField() form = TestForm(MultiDict([('zip_code', '123455')])) form.zip_code._country = u'US' </code></pre> <p>Or, overide process method and pass my extra value to it's data argument, like:</p> <pre><code>class ZIPCodeField(wtforms.TextField): def process(self, formdata, data): # we picking country value from data here pass form = TestForm(MultiDict([('zip_code', '123455')]), zip_code=zip_code={'country': u'US'}) </code></pre> <p>Which of these is proper solution? or there is better solution?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload