我是python的新手,正在尝试为Django表单创建自定义的验证码字段。我无法为此找到一个好的教学工具,因此我只是仔细研究了内置字段的代码并尝试向他们学习。我的领域有两个主要问题。首先,其小部件未显示在屏幕上。其次,当我提交表单时,Django引发AttributeError:"'CaptchaField' object has no attribute 'disabled'"
。我不确定为什么会这样。
class CaptchaField(IntegerField):
validators = [validators.ProhibitNullCharactersValidator]
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),
]
captcha =captcha_array.pop(random.randrange(len(captcha_array)))
self.captcha = captcha
def validate(self, value):
for (a,b) in captcha:
if value == b:
return True
else:
raise ValidationError(self.error_msgs['incorrect'], code = 'incorrect')
我的小部件:
class CaptchaInput(Widget):
template_name = 'django/forms/widgets/captcha.html'
def __init__(self, captcha, attrs = None):
captcha = self.captcha
attrs = self.attrs
def get_context(self, captcha, attrs = None):
return {'widget': {'captcha': captcha}}
def render(self, captcha, attrs=None):
context = self.get_context(captcha, attrs)
template = loader.get_template(self.template_name).render(context)
return mark_safe(template)
html:
<div class="card"><b>{{ a }}</b></div>
{% include django/forms/widgets/input.html %}
完整追溯:
Environment:
Request Method: POST
Request URL: http://localhost:8000/new/
Django Version: 2.1.7
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'posts']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/self/python-virtualenv/thewire/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/self/python-virtualenv/thewire/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "/home/self/python-virtualenv/thewire/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/self/python-virtualenv/thewire/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "/home/self/python-virtualenv/thewire/bin/thewire/posts/views.py" in NewPost
39. if form.is_valid():
File "/home/self/python-virtualenv/thewire/lib/python3.5/site-packages/django/forms/forms.py" in is_valid
185. return self.is_bound and not self.errors
File "/home/self/python-virtualenv/thewire/lib/python3.5/site-packages/django/forms/forms.py" in errors
180. self.full_clean()
File "/home/self/python-virtualenv/thewire/lib/python3.5/site-packages/django/forms/forms.py" in full_clean
381. self._clean_fields()
File "/home/self/python-virtualenv/thewire/lib/python3.5/site-packages/django/forms/forms.py" in _clean_fields
390. if field.disabled:
Exception Type: AttributeError at /new/
Exception Value: 'CaptchaField' object has no attribute 'disabled'
表格:
class PostForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for key in ['postTitle', 'postContent', 'category']:
self.fields[key].widget.attrs.update({'class': 'form-control'})
self.fields['postContent'].widget.attrs.update(width='100px', height='50')
class Meta:
model = Post
fields = ('postTitle', 'postContent', 'category')
captcha = forms.CaptchaField()