如何使用带有 GAE 和 Jinja2 的 WTForms 在字段无效时获得红色边框?

发布于 2024-12-20 19:35:30 字数 2769 浏览 3 评论 0原文

我已经进行了实际工作的验证,我的部分要求是,当字段无效时,无效字段周围应该有红色边框:

在此处输入图像描述

<tr><td valign="top">
      <div class="labelform" id="lname">
{% filter capitalize %}{% trans %}name{% endtrans %}{% endfilter %}:
</div></td><td>
  <div class="adinput">
{% if user or current_user %} 
    <input type="text" id="name" name="name" value="{{ current_user.name }}{% if not current_user %}{{ user.nickname() }}{% endif %}" size="35" maxlength="50" readonly/>
  {% else %}
    {{ form.name|safe }}
{% endif %}
{% if form.name.errors %}
        <ul class="errors">{% for error in form.name.errors %}<li>{{ error }}</li>{% endfor %}</ul>
    {% endif %}
  </div>
  </td></tr>

您能告诉我如何在名称字段无效的情况下实现表单字段周围的红色边框吗?这是我的表单类的 python 代码:

class AdForm(Form):

    name = TextField(_('Name'), [validators.Length(min=4, max=50,
                     message=_('Name is required'))])
    title = TextField(_('title'))
    text = TextAreaField(_('Text'), widget=TextArea())
    phonenumber = TextField(_('Phone number'))
    phoneview = BooleanField(_('Display phone number on site'))
    price = TextField(_('Price'))
    password = PasswordField(_('Password'))
    email = TextField(_('Email'))

处理表单的 HTTP POST 的代码是:

...
        form = AdForm(self.request.params)
        if form.validate():
            ad.title = form.title.data
            ad.name = form.name.data
            ad.email = form.email.data
            ad.text = form.text.data
            ad.set_password(form.password.data)
            ad.price = form.price.data
            try:
          form.price.data=form.price.data.replace(',','.').replace(' ', '')
              ad.decimal_price = form.price.data
            except:
              pass
            ad.phoneview = form.phoneview.data
            ad.url = os.environ.get('HTTP_HOST',
                                    os.environ['SERVER_NAME'])
            ad.place = self.request.get('place')
            ad.postaladress = self.request.get('place')
            ad.put()
    else:
        logging.info('form did not validate')
            self.render_jinja(
            'insert_jinja',
            facebook_app_id=facebookconf.FACEBOOK_APP_ID,
            form=form,
            form_url=blobstore.create_upload_url('/upload_form'),
            user=(users.get_current_user() if users.get_current_user() else None),
            user_url=(users.create_logout_url(self.request.uri) if users.get_current_user() else None),
            current_user=self.current_user,
            )
        return
...

你能告诉我当字段无效时我应该如何获得红色边框吗?

谢谢

I've got validation practically working and part of my requirement is that when a field is not valid there should be a red border around the field that is not valid:

enter image description here

<tr><td valign="top">
      <div class="labelform" id="lname">
{% filter capitalize %}{% trans %}name{% endtrans %}{% endfilter %}:
</div></td><td>
  <div class="adinput">
{% if user or current_user %} 
    <input type="text" id="name" name="name" value="{{ current_user.name }}{% if not current_user %}{{ user.nickname() }}{% endif %}" size="35" maxlength="50" readonly/>
  {% else %}
    {{ form.name|safe }}
{% endif %}
{% if form.name.errors %}
        <ul class="errors">{% for error in form.name.errors %}<li>{{ error }}</li>{% endfor %}</ul>
    {% endif %}
  </div>
  </td></tr>

Can you tell me how I should achieve the red border around the form field conditioned on that the name field is not valid? Here's my python code for my form class:

class AdForm(Form):

    name = TextField(_('Name'), [validators.Length(min=4, max=50,
                     message=_('Name is required'))])
    title = TextField(_('title'))
    text = TextAreaField(_('Text'), widget=TextArea())
    phonenumber = TextField(_('Phone number'))
    phoneview = BooleanField(_('Display phone number on site'))
    price = TextField(_('Price'))
    password = PasswordField(_('Password'))
    email = TextField(_('Email'))

The code that handles the HTTP POST of the form is:

...
        form = AdForm(self.request.params)
        if form.validate():
            ad.title = form.title.data
            ad.name = form.name.data
            ad.email = form.email.data
            ad.text = form.text.data
            ad.set_password(form.password.data)
            ad.price = form.price.data
            try:
          form.price.data=form.price.data.replace(',','.').replace(' ', '')
              ad.decimal_price = form.price.data
            except:
              pass
            ad.phoneview = form.phoneview.data
            ad.url = os.environ.get('HTTP_HOST',
                                    os.environ['SERVER_NAME'])
            ad.place = self.request.get('place')
            ad.postaladress = self.request.get('place')
            ad.put()
    else:
        logging.info('form did not validate')
            self.render_jinja(
            'insert_jinja',
            facebook_app_id=facebookconf.FACEBOOK_APP_ID,
            form=form,
            form_url=blobstore.create_upload_url('/upload_form'),
            user=(users.get_current_user() if users.get_current_user() else None),
            user_url=(users.create_logout_url(self.request.uri) if users.get_current_user() else None),
            current_user=self.current_user,
            )
        return
...

Can you tell me how I should get the red border when a field is invalid?

Thank you

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

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

发布评论

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

评论(1

千仐 2024-12-27 19:35:30

WTForms 中自定义小部件的文档 建议实现一个自定义小部件将一个类添加到输入元素:

class MyTextInput(TextInput):
    def __init__(self, error_class=u'has_errors'):
        super(MyTextInput, self).__init__()
        self.error_class = error_class

    def __call__(self, field, **kwargs):
        if field.errors:
            c = kwargs.pop('class', '') or kwargs.pop('class_', '')
            kwargs['class'] = u'%s %s' % (self.error_class, c)
        return super(MyTextInput, self).__call__(field, **kwargs)

然后将新的小部件用于您想要此行为的字段:

class AdForm(Form):

    name = TextField(_('Name'), [validators.Length(min=4, max=50,
                     message=_('Name is required'))], widget=MyTextInput())
    title = TextField(_('title'))
    text = TextAreaField(_('Text'), widget=TextArea())
    phonenumber = TextField(_('Phone number'))
    phoneview = BooleanField(_('Display phone number on site'))
    price = TextField(_('Price'))
    password = PasswordField(_('Password'))
    email = TextField(_('Email'))

然后将其添加到 CSS 中:

.has_errors { border: 1px solid #ff0000 }

The documentation for custom widgets in WTForms suggests implementing a custom widget that adds a class to the input element:

class MyTextInput(TextInput):
    def __init__(self, error_class=u'has_errors'):
        super(MyTextInput, self).__init__()
        self.error_class = error_class

    def __call__(self, field, **kwargs):
        if field.errors:
            c = kwargs.pop('class', '') or kwargs.pop('class_', '')
            kwargs['class'] = u'%s %s' % (self.error_class, c)
        return super(MyTextInput, self).__call__(field, **kwargs)

Then use the new widget for the fields that you want this behaviour for:

class AdForm(Form):

    name = TextField(_('Name'), [validators.Length(min=4, max=50,
                     message=_('Name is required'))], widget=MyTextInput())
    title = TextField(_('title'))
    text = TextAreaField(_('Text'), widget=TextArea())
    phonenumber = TextField(_('Phone number'))
    phoneview = BooleanField(_('Display phone number on site'))
    price = TextField(_('Price'))
    password = PasswordField(_('Password'))
    email = TextField(_('Email'))

Then add this in your CSS:

.has_errors { border: 1px solid #ff0000 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文