当前位置: 首页 > 工具软件 > Happy Captcha > 使用案例 >

django中captcha验证码的配合html使用(不使用form)

慕高阳
2023-12-01

1、安装

pip instsall django-simple-captcha

2、设置

1)在settings中,将‘captcha’注册到app列表里:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'captcha',
]

2)在settings.py文件中设置图形验证码的样式:

# django_simple_captcha 验证码配置其他配置项查看文档
# 默认格式
CAPTCHA_OUTPUT_FORMAT = '%(image)s %(text_field)s %(hidden_field)s '
CAPTCHA_NOISE_FUNCTIONS = ('captcha.helpers.noise_null', # 没有样式
    # 'captcha.helpers.noise_arcs', # 线
    # 'captcha.helpers.noise_dots', # 点
)
# 图片中的文字为随机英文字母,如 mdsh
# CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge' 
 # 图片中的文字为数字表达式,如2+2=
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'   
# 超时(minutes)
CAPTCHA_TIMEOUT = 1 
# 验证码宽度和高度
# CAPTCHA_IMAGE_SIZE = (100, 25)

3)captcha需要在数据库中建立自己的数据表,所以需要执行migrate命令生成数据表:

python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, captcha, contenttypes, sessions
Running migrations:
  Applying captcha.0001_initial... OK

4)添加url路由

在根目录下的urls.py文件中增加captcha对应的url:

urlpatterns = [
    ……
    path('captcha/', include('captcha.urls'))   # 增加这一行
]

3、django表单的形式使用:

1) forms.py文件中添加CaptchaField:

from captcha.fields import CaptchaField #提前导入CaptchaField,然后就像写普通的form字段一样添加一个captcha字段就可以了!

class UserForm(forms.Form):
  ……
    captcha = CaptchaField(label='验证码')

2)前端增加验证码栏:
复制代码

……

{% if login_form.captcha.errors %}  # 验证码错误提示
                    <div class="alert alert-warning">{{ login_form.captcha.errors }}</div>
                {% elif message %}
                    <div class="alert alert-warning">{{ message }}</div>
                {% endif %}

<div class="form-group"> #验证码输入框及显示
  {{ login_form.captcha.label_tag }}
  {{ login_form.captcha }}
</div>

其中验证图形码是否正确的工作都是在后台自动完成的,只需要使用is_valid()这个forms内置的验证方法就一起进行了,完全不需要在视图函数中添加任何的验证代码,非常方便快捷!

if login_form.is_valid():

以上表单形式对验证码的

4、普通html标签使用

1)前端
复制代码

#可分别对

  <div class="weui-cell weui-cell_vcode">
    <div class="weui-cell__hd">
        <label for="captcha_1" class="weui-label">验证码</label>
    </div>
    <div class="weui-cell__bd">
        <input class="weui-input" placeholder="请输入验证码" type="text" id="captcha_1" name="vcode" required>
        <input name="hashkey" type="hidden" value="{{hashkey}}">
    </div>
    <div class="weui-cell__ft">
        <img id="code" class="weui-vcode-img" src="{{ imgage_url }}" width="130" height="53" alt="点击刷新">
    </div>
</div>

2)view.py 后端

#先导入使用的库
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url


def login(request):
    # 验证码生成
    hashkey = CaptchaStore.generate_key()
    imgage_url = captcha_image_url(hashkey)

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        vcode = request.POST.get('vcode')
        vcode_key = request.POST.get('hashkey')
    # 验证查询数据库生成正确的码
        get_captcha = CaptchaStore.objects.get(hashkey=vcode_key)
        try:
            user = models.User.objects.get(name=username)
        except:
            message = '用户不存在!'
            return render(request, 'login/login.html', locals())

        if user.password == password:
       #将用户输入值小写后与数据库查询的response值对比:
            if vcode.lower() == get_captcha.response:
                return redirect('/')
            else:
                message = '验证码不正确!'
                return render(request, 'login/login.html', locals())
        else:
            message = '密码不正确!'
            return render(request, 'login/login.html', locals())
    else:
        return render(request, 'login/login.html', locals())
    return render(request, 'login/login.html', locals())
    
 类似资料: