1, first install pip
pip install django-simple-captcha
Because there PIL depend on the way to check there is no pil Library
pip install pillow
2, settings.py in installapp added captcha
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'post',
'user',
'captcha',
]
3, the total urls route also like to add!
urlpatterns = [
path('admin/', admin.site.urls),
#想使用命名空间 include需要传一个元组 (app路径,app名称)
url(r'^',include(('user.urls','user'),namespace='user')),
url(r'^captcha/',include('captcha.urls')),
]
captcha does not support the wording namespace
4, and then added captchaField field froms
from django import forms
from captcha.fields import CaptchaField
class UserForm(forms.Form):
username = forms.CharField(label="用户名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'}))
password = forms.CharField(label="密码", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'}))
captcha=CaptchaField(label='验证码')
5, and then configure it to log in views.py file write
from django.views import View
from user.froms import UserForm
from user.models import *
# Create your views here.
class Login(View):
def get(self,request):
capt=UserForm()
return render(request,'login.html',locals())
local () saves the current local variables within the function into a dict
6, and finally the template file is received at the variable
<form method="post" action="/login/">
{% csrf_token %}
账号:<input type="text" maxlength="20" name="username"><br>
密码:<input type="password" maxlength="20" name="password"><br>
{{ capt.captcha }}
<span style="color: red;">{{ error }}</span>
<input type="submit" value="登录">
</form>
So ok to look at open
If you can then adjust the right size
ps:
If the message OSError: can not open resource error
This problem occurs because the font is the root cause of the problem, the system font does not exist in the font that is Vera.ttf font to be called, so when looking font will be reported error, simplest and most direct way is to install what,
in fact, after installing the captcha, at its root directory already have this font path F: django project \ env \ Lib \ site-packages \ captcha \ fonts \ vear.ttf
click to install