wtforms 表单类子类化和字段排序
我有一个 UserForm 类:
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()])
并且希望在 UpdateUserForm 中将密码字段设置为可选:
class UpdateUserForm(UserForm):
password = TextField(u'Password', [validators.Optional()], widget=PasswordInput())
但密码字段放置在电子邮件字段之后,而不是之前。
子类化时如何保留字段顺序?
此外,当我尝试更改密码字段验证器时,它不起作用 - 仍然需要密码:/为什么?
class UpdateUserForm(UserForm):
def __init__(self, **kwargs):
self.password.validators = [validators.Optional()]
super(UpdateUserForm, self).__init__(**kwargs)
或
class UpdateUserForm(UserForm):
def __init__(self, **kwargs):
self.password = TextField(u'Password', [validators.Optional()], widget=PasswordInput())
super(UpdateUserForm, self).__init__(**kwargs)
一些想法...
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)
最后,我需要什么:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
关于您在迭代表单对象时重新排序字段的第一个问题,这就是我所做的:
这样,当您渲染 NewUserForm (可能来自逐个字段迭代表单渲染字段的模板)时,您会看到
用户名
、密码
、全名
。通常您会最后看到用户名
。In regards to your first question about reording the fields when iterating over the form object, this is what I did:
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 seeusername
last.我通过在
Form
类上定义一个附加的__order
属性并覆盖__iter__
方法来解决这个问题,以便首先根据返回的迭代器的数据进行排序到定义。它可能不是很有效,但是表单上没有太多字段,因此可能会导致任何问题。它还适用于子类表单中的字段。I solved this by defining an additional
__order
attribute on myForm
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.这就是我完成您想要做的事情的方法:
然后,当我实例化 UserForm 时,我在编辑时传递 update=True 。这似乎对我有用。
This is how I accomplish what were you trying to do:
Then, when I instantiate the UserForm, I pass update=True when editing. This appears to work for me.
要强制对表单字段进行排序,您可以使用以下方法:
并在表单构造函数中调用它,如下所示:
To force an ordering on the form's fields you may use the following method:
And call it within your forms constructor as follows:
发生这种情况是因为字段排序是由 UnboundField.creation_counter 类定义的,该类使用 Field 类在代码中出现的顺序。
由于这很难解决(因为 wtforms 试图使用这种方法变得神奇),因此处理此问题的最佳方法是按所需的顺序定义字段。
但如果您是完美主义者或需要遵守DRY 原则:
This happens because the fields ordering is defined by UnboundField.creation_counter class, which uses the order the Field class appears in the code.
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.
But if you are perfectionist or need to adhere to the DRY principle:
我将两个答案合并到以下代码片段中:
它是
BaseForm
上的__iter__
,我的每个表单都是其子表单。基本上,field_order
中定义的所有内容都按该顺序进行,其余字段按原样呈现。I have combined two answers into following snippet:
It's
__iter__
onBaseForm
that each of my form is child of. Basically everything that is defined infield_order
goes in that order, rest of the fields are rendered as-is.