Django 简单数学验证码,如何传递自定义字符串作为参数?

-1 投票
2 回答
1030 浏览
提问于 2025-04-18 09:16

我正在使用这个叫做django-simple-math-captcha的插件,链接在这里:https://github.com/alsoicode/django-simple-math-captcha

我已经成功配置好了它,并且它可以正常工作。实际上,这是我的代码:

from simplemathcaptcha.fields   import MathCaptchaField

class ContactForm(Form, FormMixin):
    captcha = MathCaptchaField()

根据官方文档,如果你想更改这个验证码的一些默认设置,只需要把它作为参数传入就可以了。例如,我想更改默认的问题字符串,文档中提到:

你可以选择性地传入以下参数来配置这个字段。

....

question_tmpl

一个包含格式占位符的字符串,用于显示的问题。

默认值是:"What is %(num1)i %(operator)s %(num2)i?"

...

我试着这样做:

captcha = MathCaptchaField(question_tmpl="What is the result of %(num1)i %(operator)s %(num2)i?")

但是在我添加这个更改后,django给我报了一个错误

**TypeError at /contact/**

__init__() got an unexpected keyword argument 'question_tmpl'

那么,正确的传入这个参数的方法是什么呢?

2 个回答

3

通过查看这段代码,我觉得文档写错了。目前,你需要使用MathCaptchaWidget

captcha = MathCaptchaField(widget=MathCaptchaWidget(
           question_tmpl="What is the result of %(num1)i %(operator)s %(num2)i?"))
2

如果你同时在使用django-allauth和django-simple-math-captcha这两个库,并且需要进行国际化设置的话:

首先,你需要在settings.py文件中进行一些配置:

ACCOUNT_SIGNUP_FORM_CLASS = 'your_app.forms.AllauthSignupForm'

接下来,在forms.py文件中,你也需要做一些调整:

from simplemathcaptcha.fields import MathCaptchaField
from simplemathcaptcha.widgets import MathCaptchaWidget

class AllauthSignupForm(forms.Form):
    captcha=MathCaptchaField(widget=MathCaptchaWidget(question_tmpl=_('What is %(num1)i %(operator)s %(num2)i ? ')),
    error_messages = {'invalid': _('Please check your math and try again.'), 'invalid_number': _('Enter a whole number.')})

    def signup(self, request, user):
    """ Required, or else it throws <The custom signup form must implement a "signup" method>"""
    pass    

最后,在signup.html这个模板文件中,记得更新一下内容:

{{ form.captcha }}   {{ form.captcha.errors }}

撰写回答