Django生成验证码

Django使用django-simple-captcha 生成验证码。

django-simple-captcha Github地址

安装

  1. pip install django-simple-captcha

  2. 添加captcha 到 settings.py的INSTALLED_APPSL里面。

  3. 运行python manage.py migrate 生成数据表

  4. 配置urls.py

1
2
3
urlpatterns += [
url(r'^captcha/', include('captcha.urls')),
]

引用

新建forms.py

1
2
3
4
5
6
from captcha.fields import CaptchaField

class RegisterForm(forms.Form):
email = forms.EmailField(required=True)
password = forms.CharField(required=True, min_length=6)
captcha = CaptchaField(error_messages={"invalid": u"验证码错误"})

models.py
直接验证表单是否通过,验证码字段会一并校验。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class RegisterView(View):
def get(self, request):
register_form = RegisterForm()
return render(request=request, template_name='register.html', context={"register_form": register_form})

def post(self, request):
register_form = RegisterForm(request.POST)
if register_form.is_valid():
user_profile = UserProfile()
user_name = request.POST.get('username', '')
pass_word = request.POST.get('password', '')
user_profile.username = user_name
user_profile.email = user_name
user_profile.password = make_password(password=pass_word)
else:
return render(request=request, template_name='register.html', context={"register_form": register_form})

参考资料

Django-simple-captcha Document

关注公众号 尹安灿