验证码插件--django captcha和邮箱验证机制
对于web开发在用户注册登录的环节的验证码是在开发中必不可少的一个环节,这里介绍一下我在开发中经常使用到的一个带三方的验证码插件--
captcha
一、安装
在GitHub上可以直接下载:
也可以使用pip进行安装:
二、导入
1.settings.py文件
这里需要在INSTALLED_APPS中将其注册进去:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'App01',
'crispy_forms',
'captcha',
]
2.form.py文件
因为是做用户注册使用,这里定义一个注册使用的form表单
from django import forms
from captcha.fields import CaptchaField
class RegisterForm(forms.Form):
username = forms.CharField(required=True)
password = forms.CharField(required=True,min_length=5)
email = forms.EmailField(required=True)
captcha = CaptchaField() #直接引用
3.view.py文件
from . import forms
class User_reg(View):
def get(self,request):
register_form = forms.RegisterForm
return render(request,'reg.html',{"register_form":register_form}) #form表单发送到前端进行渲染
def post(self,request):
pass
4.models.py文件
class EmailVerifyRecord(models.Model):
code = models.CharField(max_length=20,verbose_name="验证码")
email = models.EmailField(max_length=50,verbose_name="邮箱")
send_type = models.CharField(verbose_name="验证码类型",choices=(("register","注册"),("forget","找回密码")),max_length=50)
send_time = models.DateTimeField(verbose_name="发送时间",default=datetime.now)
4.reg.html页面
5.前端渲染的效果:
下面是页面的源码
后端数据库生成的id值
三、用户注册验证
1.views.py文件
from django.contrib.auth.hashers import make_password #用来将明文密码进行加密
class User_reg(View):
def get(self,request):
# register_form = forms.RegisterForm
return render(request,'reg.html',{})
def post(self,request):
register_form = forms.RegisterForm(request.POST)
if register_form.is_valid():
user_name = request.POST.get('username','')
user_email = request.POST.get("email",'')
pass_word = request.POST.get("password",'')
user_profile = models.Userinfo()
user_profile.username = user_name
user_profile.email = user_email
user_profile.password=make_password(pass_word)
user_profile.save()
send_register_email(user_email,"register")
return render(request,'login.html')
else:
return render(request,"reg.html",{"register_form":register_form})
激活
1.urls.py文件
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('^$',TemplateView.as_view(template_name="index.html"),name='index'),
url(r'^login/$',views.User_login.as_view(),name='login' ),
url(r'^reg/$',views.User_reg.as_view(),name='reg' ),
url(r'^active/(?P.*)/$',views.AciveUserView.as_view(),name='user_active'), #用户进行邮箱激活的url
]
2.views.py文件
class AciveUserView(View):
def get(self,request,active_code):
all_records = models.EmailVerifyRecord.objects.filter(code=active_code)
if all_records:
for record in all_records:
email = record.email
user = models.Userinfo.get(email=email)
user.is_active = True #这个用户表中的一个字段,用于验证用户是否进行邮政验证激活过
user.save()
return render(request,'login.html')