尝试为表单创建验证码字段

时间:2019-03-26 23:48:15

标签: django captcha

我正在尝试为表单创建一个自定义的验证码字段,除了可以在代码中选择一个随机的验证码返回最终用户以供他们解决之外,它似乎可以正常工作,则返回ValueError: too many values to unpack (expected 2)。我认为这是因为列表没有被随机化,并且python选择了整个列表以用作用户的验证码。我该如何解决这个问题?

class CaptchaField(IntegerField):
    widget = CaptchaInput
    error_msgs = { 'incorrect': _('Captcha incorrect- try again'), }

    def __init__(self):
        captcha_array = (

        ('What is the product of fifteen and four?', 60),
        ('What is four plus four?', 8),
        ('What is nine times one?', 9),
        ('How many letters are in the word orange?', 6),
        ('What is the sum of ten and two?', 12),
        ('What is the difference of eighty-four and nineteen?', 65),
        ('How many letters are in the word forest?', 6),
        ('How many letter are in the word apple?', 5),
        ('If there are four palm trees and one dies, how many are alive?', 3),
        ('What is four divided by two?', 2),
        ('How many letters are in the name of the capital of France?', 5),

        )
        captcha = random.choice(captcha_array)
        for (a,b) in captcha:
            return a 

    def validate(self, value):
        for (a,b) in captcha:
            if value == b:
                return value
            else:
                raise ValidationError(self.error_msgs['incorrect'], code = 'incorrect')

1 个答案:

答案 0 :(得分:0)

captcha = random.choice(captcha_array)返回一个元组(即('What is the product of fifteen and four?', 60))。如果只想返回字符串'What is the product of fifteen and four?',则可以执行return captcha[0]

否则,您的循环将引发ValueError

for (a,b) in captcha:
    return a 

captcha作为元组将只提供1个值,而不是2个值-首先是字符串,然后是数字。要像您那样解压值,captcha必须是一个可重复的元组(列表,字典,...)。

此外,您希望以后在captcha中访问validate吗?如果是这样,则需要将captcha保存在self中。

相关问题