【问题标题】:Trying to make a captcha field for forms尝试为表单制作验证码字段
【发布时间】: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 包装在一个列表中,而不是一个元组

标签: django captcha


【解决方案1】:

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 作为一个元组将只提供一个值,而不是两个 - 第一个字符串,然后是数字,到循环。要像 captcha 那样解压值,它必须是元组的可迭代对象(list、dict、...)。

另外,您是否希望 captcha 稍后可以在 validate 中访问?如果是这样,您需要将captcha 保存在self 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多