赞
踩
Django实现带验证码登录功能
_______________________________________________________________________
第一步安装:
- pip install django-simple-captcha
- sudo apt-get -y install libz-dev libjpeg-dev libfreetype6-dev python-dev
- pip install PIL
- pip install Pillow
第二步加载app:
- INSTALLED_APPS = (
- 'django.contrib.admin',
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- 'authpermission',
- 'DjangoUeditor',
- 'app02',
- 'captcha', # 验证码
- )
'运行
第三步同步数据库:
python manage.py migrate
第四步添加项目主url:
- urlpatterns = [
- url(r'^captcha/', include('captcha.urls')),
- ]
第五步定义表单增加验证码字段:
- from django import forms
- from captcha.fields import CaptchaField
-
-
- class RegisterForm(forms.Form):
- """
- 注册表单
- """
- username = forms.EmailField(
- widget=forms.TextInput(
- attrs={
- "class": "form-control",
- "placeholder": "请输入邮箱账号",
- "value": "",
- "required": "required"
- }
- ),
- max_length=50,
- error_messages={"required": "用户名不能为空", }
- )
- password = forms.CharField(
- widget=forms.PasswordInput(
- attrs={
- "class": "form-control",
- "placeholder": "请输入密码",
- "value": "",
- "required": "required"
- }
- ),
- min_length=8,
- max_length=50,
- error_messages={"required": "密码不能为空", }
- )
- # 验证码
- captcha = CaptchaField()
第六步在视图函数(views)中验证表单:
- def some_view(request):
- if request.POST:
- form = CaptchaTestForm(request.POST)
-
- # Validate the form: the captcha field will automatically
- # check the input
- if form.is_valid():
- human = True
- else:
- registerform = RegisterForm()
- return render(
- request, "register.html",
- {"registerform": registerform})
'运行
第七步骤html页面展示:
- {% load static %}
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Register</title>
- <script src="{% static 'js/jquery-1.12.4.min.js' %}"></script>
- <script src="{% static 'js/register.js' %}"></script>
- </head>
- <body>
- <div class="cls-content">
- <div class="cls-content-sm panel">
- <p class="pad-btm">Sign In to your account</p>
- {{ registerform }}
- <br><br>
- <input type="submit" name="submit" id="" value="注册">
-
- </div>
- </div>
- </body>
- </html>
第八步使用js动态刷新验证码:
- $(document).ready(function () {
- $(".captcha").click(function () {
- $.ajax({
- url: '/captcha/refresh/',
- type: 'GET',
- success: function (result) {
- $(".captcha").attr('src', result["image_url"]);
- $("#id_captcha_0").val(result["key"])
- }
- })
- });
- });
附加:一个挺详细的django-simple-captcha文档
https://django-simple-captcha.readthedocs.io/en/latest/usage.html
注意:以上内容是个人使用的随手记录, 就是介绍了下简单的使用
欢迎大家来吐槽,准备好瓜子饮料矿泉水,开整!!!
---------------------------------------------------------------------------------------
搞笑一则:能动手尽量别吵吵
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。