django2.0 实现验证码登录


发布时间:2019-02-15 13:08    作者: Uncle Hui   已过去:1 年,1 月   阅读总量:158 已被赞:0


验证码

 验证码库:django-simple-captcha,这里面有介绍这个第三方库的使用方法

 安装:

pip install  django-simple-captcha

Add captcha to the INSTALLED_APPS in your settings.py

INSTALLED_APPS = [
    'captcha',
]

Add an entry to your urls.py:

urlpatterns = [
    path('captcha/',include('captcha.urls')),
]

生成到数据库

python manage.py makemigrations

python manage.py migrate

可以看到数据库多了一张表

 

 在注册页面显示验证码

 定义我们的register form:

 

# users/forms.py

from captcha.fields import CaptchaField

class RegisterForm(forms.Form):
    '''注册验证表单'''    
    email = forms.EmailField(required=True)
    password = forms.CharField(required=True,min_length=5)
    # 验证码,字段里面可以自定义错误提示信息
    captcha = CaptchaField()

 

 forms.py

通过{{ register_form.captcha }}获取验证码
<div class="form-group marb8 captcha1 ">
     <label>验&nbsp;证&nbsp;码</label>
     {{ register_form.captcha }}
</div>

 

完善注册的后台逻辑

 

class RegisterView(View):
    '''用户注册'''
    def get(self,request):
        register_form = RegisterForm()
        return render(request,'register.html',{'register_form':register_form})  #这里渲染主页才会显示验证码

    def post(self,request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user_name = request.POST.get('email', None)
            # 如果用户已存在,则提示错误信息
            if UserProfile.objects.filter(email = user_name):
                return render(request, 'register.html', {'register_form':register_form,'msg': '用户已存在'})

            pass_word = request.POST.get('password', None)
            # 实例化一个user_profile对象
            user_profile = UserProfile()
            user_profile.username = user_name
            user_profile.email = user_name
            user_profile.is_active = False
            # 对保存到数据库的密码加密
            user_profile.password = make_password(pass_word)
            user_profile.save()
            send_register_eamil(user_name,'register')
            return render(request,'login.html')
        else:
            return render(request,'register.html',{'register_form':register_form})

 

点赞

0




登陆后方可评论