WTForms - 显示属性值而不是 HTML 字段

发布于 2024-11-16 18:11:44 字数 710 浏览 3 评论 0 原文

我想重复使用 WTForms 表单中的模板:

<th>${form.name.label}</th>
<td>${form.name()}</td>
...

但是,在我的编辑页面上,我希望输入字段正常显示(TextFieldSelectField、等),而在我的视图页面上,我只想显示属性的值,而不是带有该值的输入字段。

编辑页面:

<th>Name:</th>
<td><input type="text" value="Current Name" name="name" id="name"/></td>

查看页面:

<th>Name:</th>
<td>Current Name</td>

我知道我可以通过 form.name.data 访问字段的值,但是有什么方法可以使用 form.name() 保留相同的模板code> 被调用并以某种方式切换是否输出 Current Name

I want to re-use a template I have with my WTForms form:

<th>${form.name.label}</th>
<td>${form.name()}</td>
...

However, on my edit page, I want the input fields to display as normal (TextField, SelectField, etc.), while on my view page, I want to just display the value of the property, not the input field with the value.

Edit page:

<th>Name:</th>
<td><input type="text" value="Current Name" name="name" id="name"/></td>

View page:

<th>Name:</th>
<td>Current Name</td>

I know I can access a field's value via form.name.data, but is there any way I can keep the same template with form.name() being called and somehow toggle whether that outputs <input type="text"... or Current Name?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

差↓一点笑了 2024-11-23 18:11:44

我创建了一个自定义小部件:

from wtforms.fields import Field

class PlainTextWidget(object):
    def __call__(self, field, **kwargs):
        return field.data if field.data else ''

然后,对于我的视图页面,我添加了以下内容:

form = MyForm(obj=myDataRow)
fields = [val for val in form._fields]
for fieldName in fields:
    fieldProp = getattr(form, fieldName)
    setattr(fieldProp, 'widget', PlainTextWidget())

I created a custom widget:

from wtforms.fields import Field

class PlainTextWidget(object):
    def __call__(self, field, **kwargs):
        return field.data if field.data else ''

Then, for my view page, I added the following:

form = MyForm(obj=myDataRow)
fields = [val for val in form._fields]
for fieldName in fields:
    fieldProp = getattr(form, fieldName)
    setattr(fieldProp, 'widget', PlainTextWidget())
眼眸 2024-11-23 18:11:44

莎拉的上述回答让我找到了相关问题的解决方案:如果您希望某些字段是只读的怎么办?在这种情况下,您可以定义一个新的 ROTextField 变体(例如),而不是对表单对象进行运行时手术,该变体始终呈现为纯值。例如:

from wtforms.widgets import Input
from wtforms.fields import StringField

class TextOutput(Input):
    def __call__(self, field, **kwargs):
        return kwargs.get('value', field._value())

class ROTextField(StringField):
    widget = TextOutput()

现在使用 ReadOnly 属性定义您的字段:

class UserPrefs(Form):
    name     = ROTextField('name', default='Jon')
    # ...

思考这个问题帮助我更好地理解 WTForms 的工作原理。将其留在这里,以防可能帮助其他人解决相关问题。

Sarah's answer above led me to the solution to a related problem: What if you want some of your fields to be read only? In that case, instead of doing run-time surgery on the form object, you could define a new ROTextField variant (for example), that always renders to the pure value. For example:

from wtforms.widgets import Input
from wtforms.fields import StringField

class TextOutput(Input):
    def __call__(self, field, **kwargs):
        return kwargs.get('value', field._value())

class ROTextField(StringField):
    widget = TextOutput()

Now define your field with ReadOnly attributes:

class UserPrefs(Form):
    name     = ROTextField('name', default='Jon')
    # ...

Thinking about this problem helped me better understand how WTForms work. Leaving this here in case this might help someone else work through related issues.

归途 2024-11-23 18:11:44

根据 Sarah 在 WTForms-Components 中找到的答案和代码我使用以下命令快速将表单的所有字段转换为只读和禁用字段。

假设我们有一个 ProfileForm 定义如下:

class ProfileEditForm(Form):
    title = StringField("Title", validators=[validators.required("Please enter your title.")])
    first_name = StringField("First Name", validators=[validators.required("Please enter your first name.")])
    middle_name = StringField("Middle Name")
    last_name = StringField("Last Name", validators=[validators.required("Please enter your last name.")])
    organisation = StringField("Company Name", validators=[validators.required("Please enter your company name.")])
    organisation_website = StringField("Company Website")
    # more fields ...

定义以下类(基于 WTForms-Components 中的 ReadOnlyWidgetProxy):

class ReadOnlyAndDisabledWidgetProxy(object):
    def __init__(self, widget):
        self.widget = widget

    def __getattr__(self, name):
        return getattr(self.widget, name)

    def __call__(self, field, **kwargs):
        kwargs.setdefault('readonly', True)
        kwargs.setdefault('disabled', True)
        return self.widget(field, **kwargs)

现在从 ProfileForm 继承,如下所示:

class ReadOnlyProfileForm(ProfileForm):
    def __init__(self, *args, **kwargs):
        super(ReadOnlyProfileForm, self).__init__(*args, **kwargs)
        for field_name in self._fields:
            field_property = getattr(self, field_name)
            field_property.widget = ReadOnlyAndDisabledWidgetProxy(field_property.widget)

Based on Sarah's answer and code found in WTForms-Components I use the following to quickly turn all a form's fields into read-only and disabled fields.

Suppose we have a ProfileForm defined as follows:

class ProfileEditForm(Form):
    title = StringField("Title", validators=[validators.required("Please enter your title.")])
    first_name = StringField("First Name", validators=[validators.required("Please enter your first name.")])
    middle_name = StringField("Middle Name")
    last_name = StringField("Last Name", validators=[validators.required("Please enter your last name.")])
    organisation = StringField("Company Name", validators=[validators.required("Please enter your company name.")])
    organisation_website = StringField("Company Website")
    # more fields ...

Define the following class (based on ReadOnlyWidgetProxy from WTForms-Components):

class ReadOnlyAndDisabledWidgetProxy(object):
    def __init__(self, widget):
        self.widget = widget

    def __getattr__(self, name):
        return getattr(self.widget, name)

    def __call__(self, field, **kwargs):
        kwargs.setdefault('readonly', True)
        kwargs.setdefault('disabled', True)
        return self.widget(field, **kwargs)

Now inherit from ProfileForm as follows:

class ReadOnlyProfileForm(ProfileForm):
    def __init__(self, *args, **kwargs):
        super(ReadOnlyProfileForm, self).__init__(*args, **kwargs)
        for field_name in self._fields:
            field_property = getattr(self, field_name)
            field_property.widget = ReadOnlyAndDisabledWidgetProxy(field_property.widget)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文