【发布时间】:2012-01-17 18:59:34
【问题描述】:
我的表单验证工作已接近完成,我只有 2 种情况,我不知道如何解决:1)密码字段当然应该是必需的,但我也提供了使用 google 或 facebook 帐户登录的可能性通过 OAuth,然后预先填写名称,但我从表单中完全删除密码字段是否存在用户(谷歌)或 facebook 用户对象:
<tr><td>
<br /> {% if user or current_user %} {% else %}
<div class="labelform">
{% filter capitalize %}{% trans %}password{% endtrans %}{% endfilter %}:
</div>
</td><td> <div class="adinput">{{ form.password|safe }}{% trans %}Choose a password{% endtrans %}</div>{% endif %}
</td></tr>
所以对于这些已经登录并且密码字段没有意义的用户,我需要一些逻辑来使该字段有条件地可选。我在想我可以在我的表单类中有一个用于logged_in的变量+一个方法,例如:
class AdForm(Form):
logged_in = False
my_choices = [('1', _('VEHICLES')), ('2', _('Cars')), ('3', _('Bicycles'))]
name = TextField(_('Name'), [validators.Required(message=_('Name is required'))], widget=MyTextInput())
title = TextField(_('title'), [validators.Required(message=_('Subject is required'))], widget=MyTextInput())
text = TextAreaField(_('Text'),[validators.Required(message=_('Text is required'))], widget=MyTextArea())
phonenumber = TextField(_('Phone number'))
phoneview = BooleanField(_('Display phone number on site'))
price = TextField(_('Price'),[validators.Regexp('\d', message=_('This is not an integer number, please see the example and try again')),validators.Optional()] )
password = PasswordField(_('Password'),[validators.Optional()], widget=PasswordInput())
email = TextField(_('Email'), [validators.Required(message=_('Email is required')), validators.Email(message=_('Your email is invalid'))], widget=MyTextInput())
category = SelectField(choices = my_choices, default = '1')
def validate_name(form, field):
if len(field.data) > 50:
raise ValidationError(_('Name must be less than 50 characters'))
def validate_email(form, field):
if len(field.data) > 60:
raise ValidationError(_('Email must be less than 60 characters'))
def validate_price(form, field):
if len(field.data) > 8:
raise ValidationError(_('Price must be less than 9 integers'))
def validate_password(form, field):
if not logged_in and not field:
raise ValidationError(_('Password is required'))
上面的 validate_password 能否达到预期的效果?还有其他更好的方法吗?我能想到的另一种方法是有 2 个不同的表单类,在 http 帖子中我实例化了它应该是的表单类:
def post(self):
if not current_user:
form = AdForm(self.request.params)
if current_user:
form = AdUserForm(self.request.params)
I also need conditional validation for the category field, when a certain category is selected then more choices appear and these should have validation only for a certain base-category eg.用户选择“汽车”,然后通过 Ajax 可以选择汽车的注册数据和里程数,鉴于选择了汽车类别,这些字段是必需的。
所以这可能是两个问题,但两种情况都与我如何使字段“有条件可选”或“有条件要求”有关。
我的表单是这样的
对于登录用户,我预先填写了姓名和电子邮件地址,而密码字段根本没有使用,因此密码字段既不适合“可选”也不适合“必需”,它需要类似“有条件可选”或“有条件地要求。”
感谢您的任何回答或评论
【问题讨论】:
标签: python google-app-engine validation wtforms