简体   繁体   English

Django:多选表单字段的验证器

[英]Django: Validator for a multiple choice form field

I have a multiple choice field in my form where users are given a list of fields, and they can select a maximum of three choices. 我在表单中有一个多选字段,其中为用户提供了一个字段列表,他们最多可以选择三个选项。 I've defined a custom validator for restricting users from selecting more than three fields. 我定义了一个自定义验证器,用于限制用户选择三个以上的字段。

forms.py 表格

class EvangelizedForm(forms.ModelForm):
    area_of_interest = forms.CharField(
        max_length=1230,
        widget=forms.CheckboxSelectMultiple(
            choices=Evangelized.AREA_CHOICES),
        help_text="Areas of interest(Upto 3)")

I have defined a custom form validator named len_area in models.py as follows: 我在models.py中定义了一个名为len_area的自定义表单验证器,如下所示:

def len_area(li):
    if len(li) > 3:
        raise ValidationError("Please select a maximum of three fields only")

models.py models.py

class Evangelized(models.Model):
    AREA_CHOICES = (
        ('Govt', 'Govt'),
        ('Entertainment', 'Entertainment'),
        ('Automobile', 'Automobile'),
        ('Careers', 'Careers'),
        ('Books','Books'),
        ('Family', 'Family'),
        ('Food', 'Food'),
        ('Gaming', 'Gaming'),
        ('Beauty', 'Beauty'),
        ('Sports','Sports'),
        ('Events', 'Events'),
        ('Business', 'Business'),
        ('Travel', 'Travel'),
        ('Health', 'Health'),
        ('Technology','Technology'),
    ) 
    area_of_interest = models.CharField(
        max_length=1280,
        validators=[len_area])

However, the ValidationError message gets thrown at the user at all times, ie even when the selected fields are three or less than three. 但是, ValidationError消息始终会向用户抛出,即,即使所选字段为三个或小于三个也是如此。

What seems to be wrong with my validator function? 我的验证器功能似乎出了什么问题?

My guess is that value, returned by CheckboxSelectMultiple 's value_from_datadict method, is list [u'abc', u'xyz'] . 我的猜测是, CheckboxSelectMultiplevalue_from_datadict方法返回的值是列表[u'abc', u'xyz'] Then it is converted to string [u'abc', u'xyz'] by field's to_python method (actually, it is u"[u'abc', u'xyz']" ). 然后通过字段的to_python方法将其转换为字符串[u'abc', u'xyz'] (实际上,它是u"[u'abc', u'xyz']" )。 After validators are run. 验证器运行之后。 Length of this string is more than 3, that's why you got ValidationError . 该字符串的长度大于3,这就是为什么收到ValidationError的原因。

You should use ManyToManyField . 您应该使用ManyToManyField

The reason why my validator wasn't working as intended was because the argument passed to the validator, say [u'abc', u'xyz'] , was a string and not a list as I earlier thought while defining my validator. 我的验证器未按预期工作的原因是因为传递给验证器的参数说[u'abc', u'xyz']是一个字符串,而不是我在定义验证器时曾想过的列表。 As a result, as rightly pointed out by @f43d65, the length of the argument exceeded 3 every single time, and hence the ValidationError was being raised. 结果,正如@ f43d65正确指出的那样,参数的长度每次都超过3,因此引发了ValidationError

I made the following changes in my validator in order for it to work as intended: 为了使验证器按预期工作,我在验证器中进行了以下更改:

def len_area(li):
    if li.count("u'") > 3:
        raise ValidationError("Please select a maximum of three fields only")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM