使用自定义窗体字段时的AttributeError

2024-07-03 07:34:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,正在尝试为Django表单创建一个自定义captcha字段。我找不到一个很好的教学工具,所以我只是随便看看内置字段的代码,试着从中学习。我的领域有两大问题。首先,它的小部件没有显示在屏幕上。第二,当我提交表单时,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()

Tags: djangoinpyselfhomevirtualenvlibsite