Вопрос

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

Это было полезно?

Решение

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 }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top