【发布时间】:2019-03-28 02:34:53
【问题描述】:
我正在尝试为表单创建一个自定义验证码字段,它似乎工作正常,除了当代码应该选择一个随机验证码返回给最终用户让他们解决的事实,它返回一个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')
【问题讨论】:
-
尝试将您的 captcha_choices 包装在一个列表中,而不是一个元组