当对一个字段使用wtform验证时,“不是有效的选择”是什么意思?

2024-04-25 10:05:13 发布

您现在位置:Python中文网/ 问答频道 /正文

当对动态选项(其中一个选择字段中的选项依赖于另一个选择字段中的选项)使用验证时,我收到了一条不可理解的错误消息。但是,一旦选择了一个地区,我就不能选择一个城市。为什么不?必须做什么?在

 for city in montaomodel.City.all().fetch(99999):  # TODO: only do this for the region
     try:
         form.area.choices.insert(long(city.key().id()),
         (str(city.key().id()), 'Select...'))
     except:
         pass

插入和验证的整个代码块如下所示。在

^{pr2}$

我的表单类如下所示。在

class AdForm(Form):
    categories = [
        ('1', _('All categories')),
        ('disabled', _('VEHICLES')),
        ('2010', _('Cars')),
        ('3', _('Motorcycles')),
        ('4', _('Accessories & Parts')),
        ('disabled', _('PROPERTIES')),
        ('7', _('Apartments')),
        ('8', _('Houses')),
        ('9', _('Commercial properties')),
        ('10', _('Land')),
        ('disabled', _('ELECTRONICS')),
        ('12', _('Mobile phones & Gadgets')),
        ('13', _('TV/Audio/Video/Cameras')),
        ('14', _('Computers')),
        ('disabled', _('HOME & PERSONAL ITEMS')),
        ('16', _('Home & Garden')),
        ('17', _('Clothes/Watches/Accessories')),
        ('18', _('For Children')),
        ('disabled', _('LEISURE/SPORTS/HOBBIES')),
        ('20', _('Sports & Outdoors')),
        ('21', _('Hobby & Collectables')),
        ('22', _('Music/Movies/Books')),
        ('23', _('Pets')),
        ('20', _('BUSINESS TO BUSINESS')),
        ('24', _('Hobby & Collectables')),
        ('25', _('Professional/Office equipment')),
        ('26', _('Business for sale')),
        ('disabled', _('JOBS & SERVICES')),
        ('28', _('Jobs')),
        ('29', _('Services')),
        ('30', _('Events & Catering')),
        ('31', _('Others')),
        ('1000', _('Sports & Outdoors')),
        ('1010', _('Hobby & Collectables')),
        ('1020', _('Hobby & Collectables')),
        ('1030', _('Music/Movies/Books')),
        ('1050', _('Pets')),
        ('1080', _('BUSINESS TO BUSINESS')),
        ('1100', _('Hobby & Collectables')),
        ('1090', _('Professional/Office equipment')),
        ('2010', _('Business for sale')),
        ('2030', _('Sports & Outdoors')),
        ('2040', _('Hobby & Collectables')),
        ('2080', _('Music/Movies/Books')),
        ('2070', _('Pets')),
        ('3000', _('BUSINESS TO BUSINESS')),
        ('3040', _('Hobby & Collectables')),
        ('3050', _('Professional/Office equipment')),
        ('3060', _('Business for sale')),
        ('4000', _('Sports & Outdoors')),
        ('4010', _('Hobby & Collectables')),
        ('4020', _('Music/Movies/Books')),
        ('4040', _('Pets')),
        ('4030', _('BUSINESS TO BUSINESS')),
        ('4090', _('Hobby & Collectables')),
        ('4060', _('Professional/Office equipment')),
        ('4070', _('Business for sale')),
        ('5030', _('Music/Movies/Books')),
        ('5020', _('Pets')),
        ('5010', _('BUSINESS TO BUSINESS')),
        ('5040', _('Hobby & Collectables')),
        ('6010', _('Professional/Office equipment')),
        ('6020', _('Business for sale')),
        ('6030', _('Music/Movies/Books')),
        ('6040', _('Pets')),
        ('7010', _('BUSINESS TO BUSINESS')),
        ('Other', _('Hobby & Collectables')),
    ]

    regions = [('', _('Choose')), ('3', _('Delhi')), ('4', _('Maharasta'
    )), ('7', _('Gujarat'))]
    cities = [('', _('«Choose city»')), ('3', _('Mumbai')), ('4',
                                                             _('Delhi'))]
    nouser = HiddenField(_('No user'))  # dummy variable to know whether user is logged in
    name = TextField(_('Name'),
                     [validators.Required(message=_('Name is required'
                     ))], widget=MontaoTextInput())
    title = TextField(_('Subject'),
                      [validators.Required(message=_('Subject is required'
                      ))], widget=MontaoTextInput())
    text = TextAreaField(_('Ad text'),
                         [validators.Required(message=_('Text is required'
                         ))], widget=MontaoTextArea())
    phonenumber = TextField(_('Phone'), [validators.Optional()])
    type = TextField(_('Type'),
                     [validators.Required(message=_('Type is required'
                     ))])
    phoneview = BooleanField(_('Display phone number on site'))
    price = TextField(_('Price'), [validators.Regexp('^[0-9]+$',
                                                     message=_(
                                                         'This is not an integer number, please see the example and try again'
                                                     )), validators.Optional()], widget=MontaoTextInput())
    email = TextField(_('Email'),
                      [validators.Required(message=_('Email is required'
                      )),
                       validators.Email(message=_('Your email is invalid'
                       ))], widget=MontaoTextInput())

    area = SelectField(_('City'), choices=cities,
                       validators=[validators.Optional()])
    category_group = SelectField(_('Category'), choices=categories,
                                 validators=[validators.Required(message=_('Category is required'
                                 ))])

    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_area(form, field):
        if len(field.data) > 888:
            raise ValidationError(_('Dummy validator'
            ))

Tags: tofieldmessageforismusicbusinessmovies
1条回答
网友
1楼 · 发布于 2024-04-25 10:05:13

这里有一个代码示例(1个省有N个城市):

class ProvinceField(forms.ModelChoiceField):
    def __init__(self, query=Province.objects.all().order_by('name')):
        super(ProvinceField, self).__init__(queryset=query)

class CityField(forms.ModelChoiceField):    
    def __init__(self, query=City.objects.none()):
        super(CityField, self).__init__(queryset=query)

class CityForm(forms.Form)):
    province = ProvinceField()
    city = CityField()

    def __init__(self, *args, **kwargs):
        super(CityForm, self).__init__(*args, **kwargs)            
        if kwargs and kwargs.get('data').get('province'):
            try:
                province = Province.objects.get(pk=kwargs.get('data').get('province'))
            except ObjectDoesNotExist:
                self.fields['city'].queryset = City.objects.none()
            else:
                self.fields['city'].queryset = province.cities.all().order_by('name')
        else:
            self.fields['city'].queryset = City.objects.none()

希望这段代码能对你有所帮助!在

相关问题 更多 >