26.Django图形验证码

Django原生没有支持图形验证码,需要我们使用第三方库django-simple-captcha, 当然也可以自己 开发,简单期间我们使用django-simple-captcha.

安装

pip install django-simple-captcha

同时会安装six、olefile和Pillow。

settings.py中注册

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

    'captcha',
]

同步数据库

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

添加urls.py

from django.urls import path, include
from demo.views import index

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

views.py

from .forms import UserForm

def index(request):
    form = UserForm()

    return render(request, 'index.html', {'form':form})

模版中添加

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/">
    {% csrf_token %}
    {{ form }}
</form>
</body>
</html>

声明:原创文章,版权所有,转载请注明出处,https://litets.com。