Skip to main content
 首页 » 编程设计

python之如何在 Django 的 Crispy Form 中添加 CaptchaField()

2025年05月04日33lexus

我在我的 Django 应用程序中使用包 django-simple-captcha。

documentation指出要在表单中添加验证码字段,您需要做的就是

from django import forms 
from captcha.fields import CaptchaField 
 
class CaptchaTestForm(forms.Form): 
    myfield = AnyOtherField() 
    captcha = CaptchaField() 

但是,如果我的表格是脆皮表格,我该如何使用这样的字段,如下 -

class SignupForm(authtoolsforms.UserCreationForm): 
 
    def __init__(self, *args, **kwargs): 
        super(SignupForm, self).__init__(*args, **kwargs) 
        self.helper = FormHelper() 
        self.fields["email"].widget.input_type = "email" 
 
        self.helper.layout = Layout( 
            Field('email', placeholder="Enter Email", autofocus=""), 
            Field('name', placeholder="Enter Full Name"), 
            Field('password1', placeholder="Enter Password"), 
            Field('password2', placeholder="Re-enter Password"), 
            Field('gender', placeholder="Gender"), 
            Submit('sign_up', 'Sign up', css_class="btn-warning"), 
            ) 

请您参考如下方法:

class SignupForm(authtoolsforms.UserCreationForm): 
    captcha = CaptchaField() 
 
    def __init__(self, *args, **kwargs): 
        super(SignupForm, self).__init__(*args, **kwargs) 
        self.helper = FormHelper() 
        self.fields["email"].widget.input_type = "email" 
 
        self.helper.layout = Layout( 
            Field('email', placeholder="Enter Email", autofocus=""), 
            Field('name', placeholder="Enter Full Name"), 
            Field('password1', placeholder="Enter Password"), 
            Field('password2', placeholder="Re-enter Password"), 
            Field('gender', placeholder="Gender"), 
            Field('captcha ', placeholder="Enter captcha"), 
            Submit('sign_up', 'Sign up', css_class="btn-warning"), 
            )