django使用django-simple-captcha模块为窗体加上防机器人验证机制

1.安装captcha
  pip install django-simple-captcha
  (在win10,pycharm,python3.8的环境中,可能安装失败,解决方法:指定版本号,如pip install django-simple-captcha==0.4.6)
   接下来还要确定Pillow是否已经安装在系统中,可以使用pip list检查一下
  

 2.在settings.py 配置captcha的相关信息

    首先在INSTALL_APPS中添加captcha验证码功能,项目运行时会自动加载catpcha功能,然后对captcha功能进行相关的配置,主要的配置有:验证码的显示顺序,图片噪点,图片大小,背景颜色和验证码内容(当然也可以使用默认配置);具体配置如下:

         

 

   代码如下:

# django_simple_captcha 验证码基本配置
# 设置验证码的显示顺序,一个验证码识别包含文本框,隐藏域和验证码图片,该配置用于设置三者的显示顺序
CAPTCHA_OUTPUT_FORMAT = '%(text_field)s %(hidden_field)s %(image)s'
# 设置图片噪点
CAPTCHA_NOISE_FUNCTIONS = (
    # 设置样式
    'captcha.helpers.noise_null',
    # 设置干扰线
    'captcha.helpers.noise_arcs',
    # 设置干扰点
    'captcha.helpers.noise_dots'
)

# (验证码图片)图片大小
CAPTCHA_IMAGE_SIZE = (100, 25)
# 设置图片背景颜色
CAPTCHA_BACKGROUND_COLOR = '#ffffff'
# 图片中的文字为随机英文字母,如mdsh
#CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge'
# 图片中的文字为英文单词
# CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.word_challenge'
# 图片中的文字为数字表达式,如1+2= </span>
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'
# 设置字符个数
CAPTCHA_LENGTH = 4
# 设置超时(minutes)
CAPTCHA_TIMEOUT = 1

  完成上述配置后,要执行数据迁移。 即执行python manage.py migrate指令,会生成一个captcha_captchastore的数据表。

 

3.定义用户登录表单类:

        

 

 代码如下:

class LoginForm(forms.Form):
    user_name = forms.CharField(label='姓名', max_length=10)
    user_password = forms.CharField(label='密码', widget=forms.PasswordInput)
    captcha = CaptchaField()

 

视图函数如下:

 

def login(request):
    if request.method == 'POST':
        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():
            login_name = request.POST.get('user_name')
            login_password = request.POST.get('user_password')

            user = authenticate(username=login_name, password=login_password)
            if user is not None:
                if user.is_active:
                    auth.login(request, user)
                    messages.add_message(request, messages.SUCCESS, '成功登录了11')
                    return redirect('/')
                else:
                    messages.add_message(request, messages.WARNING, '账号尚未启动')
            else:
                messages.add_message(request, messages.WARNING, '登陆失败')

        else:
            messages.add_message(request, messages.INFO, '请检查输入的字段内容')
    else:
        login_form = forms.LoginForm()

    return render(request, 'login.html', locals())



def ajax_val(request):
    if request.is_ajax():
        response = request.GET['response']
        hashkey = request.GET['hashkey']

        cs = CaptchaStore.objects.filter(response=response,hashkey=hashkey)
        if cs:
            json_data = {'status': 1}
        else:
            json_data = {'status': 0}
        return JsonResponse(json_data)

    else:
        json_data = {'status': 0}
        return JsonResponse(json_data)

 

 在urls.py加入路径,   path('login/', views.login, name='login'),path('ajax_val/',views.ajax_val),

 

 接下来看login.html的代码:

{% extends 'base.html' %}
{% block title %}登录分享日记{% endblock %}
{% block content %}
<div class="container">
{% if message %}
    <div class="alert alert-warning">{{ message }}</div>
{% endif %}

{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading" align="cetnter">
                <h3>登陆我的私人日记</h3>
            </div>
        </div>
    </div>
</div>
<form action="." method="post">
    {% csrf_token %}
    <table>
        <tr>
            <td>用户名:</td>
            <td>{{ login_form.user_name }}</td>
        </tr>

        <tr>
            <td>密码:</td>
            <td>{{ login_form.user_password }}</td>
        </tr>

        <tr>
            <td>验证码:</td>
            <td>{{ login_form.captcha }}</td>
        </tr>
    </table>
    <input type="submit" value="登录"><br>
</form>
</div> 
<script> 

$(function(){ 
// 动态刷新验证码 
  $('.captcha').click(function (){ 
    $.getJSON("/captcha/refresh/", function(result){ 
      $('.captcha').attr('src', result['image_url']); 
      $('#id_captcha_0').val(result['key']) 
    }); 
  }); 
// 动态验证验证码 
  $('#id_captcha_1').blur(function(){ 
    $('#captcha_status').remove(); 
    json_data = { 
      'response': $('#id_captcha_1').val(), 
      'hashkey': $('#id_captcha_0').val() 
      } 
    $.getJSON('/ajax_val/',json_data,function(data){ 
      if(data['status']){ 
        $('#id_captcha_1').after('<span id="captcha_status">*验证码正确</span>') 
      }else{ 
        $('#id_captcha_1').after('<span id="captcha_status">*验证码错误</span>') 
      } 
    }) 
  }); 
});
 </script> 
{% endblock %}

 

  其中模板变量login_form.captcha 会生成的html内容如下:

 <input autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" id="id_captcha_1" name="captcha_1" type="text">
 <input id="id_captcha_0" name="captcha_0" type="hidden" value="e11dad77e41ef5f9d87d5ce989343704d46bf33f">
 <img src="/captcha/image/e11dad77e41ef5f9d87d5ce989343704d46bf33f/" alt="captcha" class="captcha">

 

官方文档: https://django-simple-captcha.readthedocs.io/en/latest/






 


 

 
{% extends 'base.html' %} {% block title %}登录分享日记{% endblock %} {% block content %} <div class="container"> {% if message %}     <div class="alert alert-warning">{{ message }}</div> {% endif %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} <div class="row">     <div class="col-md-12">         <div class="panel panel-default">             <div class="panel-heading" align="cetnter">                 <h3>登陆我的私人日记</h3>             </div>         </div>     </div> </div> <form action="." method="post">     {% csrf_token %}     <table>         <tr>             <td>用户名:</td>             <td>{{ login_form.user_name }}</td>         </tr>         <tr>             <td>密码:</td>             <td>{{ login_form.user_password }}</td>         </tr>         <tr>             <td>验证码:</td>             <td>{{ login_form.captcha }}</td>         </tr>     </table>     <input type="submit" value="登录"><br> </form> </div> <script> $(function(){ // 动态刷新验证码 $('.captcha').click(function (){ $.getJSON("/captcha/refresh/", function(result){ $('.captcha').attr('src', result['image_url']); $('#id_captcha_0').val(result['key']) }); }); // 动态验证验证码 $('#id_captcha_1').blur(function(){ $('#captcha_status').remove(); json_data = { 'response': $('#id_captcha_1').val(), 'hashkey': $('#id_captcha_0').val() } $.getJSON('/ajax_val/',json_data,function(data){ if(data['status']){ $('#id_captcha_1').after('<span id="captcha_status">*验证码正确</span>') }else{ $('#id_captcha_1').after('<span id="captcha_status">*验证码错误</span>') } }) }); });  </script> {% endblock %}
[{% Extends'base.Html' %} {% block title%} dēnglù fēnxiǎng rìjì {% endblock%} {% block content%} <div class="container"> {% if message%} <div class="alert alert-warning">{{message}}</div> {% endif%} {% for message in messages%} <div class="alert alert-{{message.Tags}}"> {{message}} </div> {% endfor%} <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading" align="cetnter"> <h3>dēnglù wǒ de sīrén rìjì </h3> </div> </div> </div> </div> <form action="." Method="post"> {% csrf_token%} <table> <tr> <td>yònghù míng:</Td> <td>{{login_form.User_name}}</td> </tr> <tr> <td>mìmǎ:</Td> <td>{{login_form.User_password}}</td> </tr> <tr> <td>yànzhèng mǎ:</Td> <td>{{login_form.Captcha}}</td> </tr> </table> <input type="submit" value="dēnglù"><br> </form> </div> <script> $(function(){ // dòngtài shuāxīn yànzhèng mǎ $('.Captcha').Click(function (){ $.GetJSON("/captcha/refresh/", function(result){ $('.Captcha').Attr('src', result['image_url']); $('#id_captcha_0').Val(result['key']) }); }); // dòngtài yànzhèng yànzhèng mǎ $('#id_captcha_1').Blur(function(){ $('#captcha_status').Remove(); json_data = { 'response': $('#Id_captcha_1').Val(), 'hashkey': $('#Id_captcha_0').Val() } $.GetJSON('/ajax_val/',json_data,function(data){ if(data['status']){ $('#id_captcha_1').After('<span id="captcha_status">*yànzhèng mǎ zhèngquè </span>') }else{ $('#id_captcha_1').After('<span id="captcha_status">*yànzhèng mǎ cuòwù </span>') } }) }); }); </script> {% endblock%}]
{% Extends 'base.html'%}
{% Block title%} Log in to share diary {% endblock%}
{% Block content%}
<Div class = "container">
{% If message%}
    <Div class = "alert alert-warning"> {{message}} </ div>
{% Endif%}

{% For message in messages%}
<Div class = "alert alert - {{message.tags}}">
{{Message}}
</ Div>
{% Endfor%}
<Div class = "row">
    <Div class = "col-md-12">
        <Div class = "panel panel-default">
            <Div class = "panel-heading" align = "cetnter">
                <H3> visit my private diary </ h3>
            </ Div>
        </ Div>
    </ Div>
</ Div>
<Form action = "." Method = "post">
    {% Csrf_token%}
    <Table>
        <Tr>
            <Td> Username: </ td>
            <Td> {{login_form.user_name}} </ td>
        </ Tr>

        <Tr>
            <Td> Password: </ td>
            <Td> {{login_form.user_password}} </ td>
        </ Tr>

        <Tr>
            <Td> codes: </ td>
            <Td> {{login_form.captcha}} </ td>
        </ Tr>
    </ Table>
    <Input type = "submit" value = "Login"> <br>
</ Form>
</ Div>
<Script>

$ (Function () {
// dynamic refresh code
$ ( '. Captcha'). Click (function () {
$ .GetJSON ( "/ captcha / refresh /", function (result) {
. $ ( '. Captcha') attr ( 'src', result [ 'image_url']);
$ ( '# Id_captcha_0'). Val (result [ 'key'])
});
});
// dynamic verification code
$ ( '# Id_captcha_1'). Blur (function () {
$ ( '# Captcha_status') remove ().;
json_data = {
'Response': $ ( '# id_captcha_1') val (),.
'Hashkey': $ ( '# id_captcha_0') val ().
}
$ .GetJSON ( '/ ajax_val /', json_data, function (data) {
if (data [ 'status']) {
$ ( '# Id_captcha_1'). After ( '<span id = "captcha_status"> * code is correct </ span>')
} Else {
$ ( '# Id_captcha_1'). After ( '<span id = "captcha_status"> * error codes </ span>')
}
})
});
});
 </ Script>
{% Endblock%}
posted @ 2020-03-04 18:07  本人小白  阅读(552)  评论(0编辑  收藏  举报