Python 版本:3.6.0 和 Django 版本:1.10.5
我阅读了所有关于 Django-simple-captcha 的文档,我只是找到这句话来修改验证码的渲染:
(用于默认为:u'%(image)s %(hidden_field)s %(text_field)s')
我不想更改所有验证码的模式,我只需要像其他字段一样在 forms.py 中添加attrs={}来更改当前验证码。
工作的常规语法示例:
name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
目前,我有类似这样的验证码:渲染 HTML 中的img + 文本字段。如果可能的话,我想要文档之类的东西。
我在forms.py中使用:
class RegisterForm(forms.ModelForm):
...
captcha = CaptchaField(label='Are you an human? ')
在 page.html 中:
<div class="fieldWrapper input-field col-xs-12">
<i class="material-icons">person_pin</i>
<label for="id_captcha">{{ form.captcha.label }}</label>
{{ form.captcha }}
</div>
CaptchaField 渲染是 3 个不同的字段,默认的 HTML 渲染是(浏览器中的代码):
<img src="/captcha/image/f5dc943d14ecb5674a1490468567bcb186178228/" alt="captcha" class="captcha">
<input id="id_captcha_0" name="captcha_0" type="hidden" value="f5dc943d14ecb5674a1490468567bcb186178228">
<input autocomplete="off" id="id_captcha_1" name="captcha_1" type="text">
我试图找到在小部件验证码中使用参数“attrs”为文本字段添加 CSS 的可能性,就像其他 Django 字段一样。所以我在我的 form.py 中尝试了类似的东西:
captcha = CaptchaField(label='Are you an human? ', widget=forms.TextInput(attrs={'class':'white-text'}))
但它不起作用,因为由 captchafield() 生成的默认字段被其他字段文本字段替换(并且验证验证码的 id 是错误的,或者我只有我的文本字段而不是图片)。
因此,我继续搜索解决方案,并尝试了解有关 CaptchaField 结构的组成:
captcha.__dict__
{'require_all_fields': True, 'required': True, 'label': 'Are you an human ? ', 'initial': None, 'show_hidden_initial': False, 'help_text': '', 'disabled': False, 'label_suffix': None, 'localize': False, 'widget': <captcha.fields.CaptchaTextInput object at 0x000001F929C16198>, 'creation_counter': 28, 'error_messages': {'required': <django.utils.functional.lazy.<locals>.__proxy__ object at 0x000001F9290A4828>, 'invalid': <django.utils.functional.lazy.<locals>.__proxy__ object at 0x000001F929C16E48>, 'incomplete': <django.utils.functional.lazy.<locals>.__proxy__ object at 0x000001F9290ED080>}, 'validators': [], 'fields': (<django.forms.fields.CharField object at 0x000001F929C16080>, <django.forms.fields.CharField object at 0x000001F929C167B8>)}
captcha.__dict__.keys()
dict_keys(['require_all_fields', 'required', 'label', 'initial', 'show_hidden_initial', 'help_text', 'disabled', 'label_suffix', 'localize', 'widget', 'creation_counter', 'error_messages', 'validators', 'fields'])
所以我搜索在我的 TextInput 字段中添加“attrs”参数:
captcha.widget.widgets[1]
<django.forms.widgets.TextInput object at 0x000001F929C16EB8>
captcha.widget.widgets[1].__dict__
{'attrs': {}}
现在我尝试修改构造渲染的字段 TextInput 的属性,所以我看到了在文档上构建 3 个字段的MultiWidget:
class BaseCaptchaTextInput(MultiWidget):
"""
Base class for Captcha widgets
"""
def __init__(self, attrs=None):
widgets = (
HiddenInput(attrs),
TextInput(attrs),
)
super(BaseCaptchaTextInput, self).__init__(widgets, attrs)