19

I have a UserForm class:

class UserForm(Form):
    first_name = TextField(u'First name', [validators.Required()])
    last_name = TextField(u'Last name', [validators.Required()])
    middle_name = TextField(u'Middle name', [validators.Required()])
    username = TextField(u'Username', [validators.Required()])
    password = TextField(u'Password', [validators.Required()], widget=PasswordInput())
    email = TextField(u'Email', [validators.Optional(), validators.Email()])

and want to make the password field Optional in UpdateUserForm:

class UpdateUserForm(UserForm):
    password = TextField(u'Password', [validators.Optional()], widget=PasswordInput())

But the password field is placed after the email field, not before.

How do I preserve field order when subclassing?

Additionally, when I try to change the password field validators it doesn't work - password still Required :/ Why?

class UpdateUserForm(UserForm):
    def __init__(self, **kwargs):
        self.password.validators = [validators.Optional()]
        super(UpdateUserForm, self).__init__(**kwargs)

or

class UpdateUserForm(UserForm):
    def __init__(self, **kwargs):
        self.password = TextField(u'Password', [validators.Optional()], widget=PasswordInput())
        super(UpdateUserForm, self).__init__(**kwargs)

Some thoughts...

class UpdateUserForm(UserForm):
    def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
        self._unbound_fields[4][1] = TextField(u'Password', [validators.Optional()], widget=PasswordInput())
        UserForm.__init__(self, formdata=None, obj=None, prefix='', **kwargs)

Finally, what I need:

class UpdateUserForm(UserForm):
    def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
        UserForm.__init__(self, formdata, obj, prefix, **kwargs)
        self['password'].validators = [validators.Optional()]
        self['password'].flags.required = False
2
  • 1
    Is this question solved? How do you render the form? Where do you need the right order? Dec 12, 2011 at 22:12
  • why does the order matter? how are you printing out the form in your page? i don't think python guarantees any specific order (other than maybe alphabetical?) when it comes to object attributes. additionally, i find when making a user profile editor, it's best to put the password change form on a second page and provide a link to it since ideally you'll want to make the user confirm their password choice and you don't want them to accidentally update their password without an explicit option for it.
    – tkone
    Dec 12, 2011 at 22:13

6 Answers 6

13

In regards to your first question about reording the fields when iterating over the form object, this is what I did:

class BaseForm(Form):
    def __iter__(self):
        field_order = getattr(self, 'field_order', None)
        if field_order:
            temp_fields = []
            for name in field_order:
                if name == '*':
                    temp_fields.extend([f for f in self._unbound_fields if f[0] not in field_order])
                else:
                    temp_fields.append([f for f in self._unbound_fields if f[0] == name][0])
            self._unbound_fields = temp_fields
        return super(BaseForm, self).__iter__()

class BaseUserForm(BaseForm):
    password = PasswordField('Password', [Required()])
    full_name = TextField('Full name', [Required()])

class NewUserForm(BaseUserForm):
    username = Textfield('Username', [Required()])
    field_order = ('username', '*')

That way, when you render NewUserForm (perhaps from a template which iterates over the form rendering field by field), you'll see username, password, full_name. Normally you'd see username last.

4
  • This works exactly as I was looking for, thanks rhyek!
    – squeegee
    Oct 30, 2013 at 20:15
  • Not sure if it's related to changes on the wtforms or anything else. But it seems that self._unbound_fields is not a attribute that need to be replaced. One should modify self._fields, as those fields are already bounded and we are in the middle of rendering (probably). Feb 12, 2016 at 14:40
  • This worked on WTForms 1.x, but internal changes stopped it working at some point when the Form.__iter__() was removed. Moving the ordering of _unbound_fields into the init__() before calling super.__init appears to work.
    – Mark
    Oct 19, 2017 at 3:02
  • 1
    For newer versions of WTForms I fixed this by adding the following line: self._fields = OrderedDict((k[0], self._fields[k[0]]) for k in self._unbound_fields) after the line: self._unbound_fields = temp_fields (with the appropriate collections imports, of course)
    – Attack68
    Sep 27, 2018 at 12:06
4

I solved this by defining an additional __order attribute on my Form class, and overriding the __iter__ method so that the returned iterator's data is sorted first according to the definition. It might not be quite efficient, but there are not that many fields on a form, that it could cause any problem. It also works with fields from subclassed forms.

class MyForm(Form):
    field3 = TextField()
    field1 = TextField()
    field2 = TextField()

    __order = ('field1', 'field2', 'field3')

    def __iter__(self):
        fields = list(super(MyForm, self).__iter__())
        get_field = lambda field_id: next((fld for fld in fields
                                           if fld.id == field_id))
        return (get_field(field_id) for field_id in self.__order)
3
  • I love how simple this is— but now I get a CSRF error when using {{form.hidden_tag}} in my template. Seems like this screws up its ability to find the tag?
    – jwdink
    Oct 5, 2015 at 22:37
  • To fix CSRF error: __order = ('csrf_token', 'field1', 'field2', 'field3') Oct 18, 2017 at 18:26
  • while using wtform-alchemy with only field, reusing only, instead of writing __order again for field_id in __class__.Meta.only
    – rho
    Feb 12, 2018 at 9:19
3

This is how I accomplish what were you trying to do:

class UserForm(wtforms.Form):                                                   
    def __init__(self, *args, **kwargs):                                        
        super(UserForm,self).__init__(*args, **kwargs)                          

        if kwargs.get('update', None):                                          
            self['passwd'].validators.append(wtforms.validators.Optional())
            self['passwd'].flags.required = False     
        else:                                                                   
            self['passwd'].validators.append(wtforms.validators.Required()) 

    passwd = UnicodeField(                                                      
        u'Password',                                                            
        [                                                                       
            wtforms.validators.length(max=50),                                  
            wtforms.validators.EqualTo(                                         
                'confirm',                                                      
                message='Passwords must match'                                  
                )                                                               
            ],                                                                  
        widget = wtforms.widgets.PasswordInput()                                
        )                                                                       

    confirm = wtforms.PasswordField(u'Password Verify')

Then, when I instantiate the UserForm, I pass update=True when editing. This appears to work for me.

3

To force an ordering on the form's fields you may use the following method:

from collections import OrderedDict

def order_fields(fields, order):
    return OrderedDict((k,fields[k]) for k in order)

And call it within your forms constructor as follows:

class FancyForm(Form, ParentClass1, ParentClass2...):
    x = TextField()
    y = TextField()
    z = TextField()

    _order = 'x y z'.split()


    def __init__(self, *args, **kwargs):
        super(FancyForm, self).__init__(*args, **kwargs)
        self._fields = order_fields(self._fields, 
                                    self._order + ParentClass1._order + ParentClass2._order)
0
2

This happens because the fields ordering is defined by UnboundField.creation_counter class, which uses the order the Field class appears in the code.

>>> x1 = UserForm()
>>> x2 = UpdateUserForm()
>>> [(f[0], f[1].creation_counter) for f in x1._unbound_fields]
[('first_name', 22), ('last_name', 23), ('middle_name', 24), ('username', 25), ('password', 26), ('email', 27)]
>>> [(f[0], f[1].creation_counter) for f in x2._unbound_fields]
[('first_name', 22), ('last_name', 23), ('middle_name', 24), ('username', 25), ('email', 27), ('password', 28)]
>>> 

As this is hard to solve (because wtforms try to be magic using this approach), the best way to deal with this is to define the fields in the desired order.

class BaseForm(Form):
    first_name = TextField(u'First name', [validators.Required()])
    last_name = TextField(u'Last name', [validators.Required()])
    middle_name = TextField(u'Middle name', [validators.Required()])
    username = TextField(u'Username', [validators.Required()])

class UserForm(BaseForm):
    password = TextField(u'Password', [validators.Required()], widget=PasswordInput())
    email = TextField(u'Email', [validators.Optional(), validators.Email()])

class UpdateUserForm(BaseForm):
    password = TextField(u'Password', [validators.Optional()], widget=PasswordInput())
    email = TextField(u'Email', [validators.Optional(), validators.Email()])

But if you are perfectionist or need to adhere to the DRY principle:

class BaseForm(Form):
    first_name = TextField(u'First name', [validators.Required()])
    last_name = TextField(u'Last name', [validators.Required()])
    middle_name = TextField(u'Middle name', [validators.Required()])
    username = TextField(u'Username', [validators.Required()])

class UserForm(BaseForm):
    password = TextField(u'Password', [validators.Required()], widget=PasswordInput())

class UpdateUserForm(BaseForm):
    password = TextField(u'Password', [validators.Optional()], widget=PasswordInput())

BaseForm.email = TextField(u'Email', [validators.Optional(), validators.Email()])
1

I have combined two answers into following snippet:

def __iter__(self):
    ordered_fields = collections.OrderedDict()

    for name in getattr(self, 'field_order', []):
        ordered_fields[name] = self._fields.pop(name)

    ordered_fields.update(self._fields)

    self._fields = ordered_fields

    return super(BaseForm, self).__iter__()

It's __iter__ on BaseForm that each of my form is child of. Basically everything that is defined in field_order goes in that order, rest of the fields are rendered as-is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.